﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Threading;

namespace DBSynchronize
{
    /// <summary>
    /// Класс для работы с коллекциями объектов из базы данных
    /// </summary>
    public static class DB
    {
        /// <summary>
        /// Коллекции сущностей базы данных
        /// </summary>
        private static CRMEntities1 _entities;

        /// <summary>
        /// Коллекции сущностей базы данных
        /// </summary>
        public static CRMEntities1 Entities
        {
            get
            {
                if (_entities == null)
                {
                    _entities = new CRMEntities1();
                }
                return _entities;
            }
            set { _entities = value; }
        }


        /// <summary>
        /// Сохранение в базу
        /// </summary>
        public static void Save()
        {
            try
            {
                Entities.SaveChanges();
            }
            catch
            {
                Entities = new CRMEntities1();
            }
        }


        /// <summary>
        /// Текущий язык в системе
        /// </summary>
        public static CurrentLanguage CurrentLanguage
        {
            get
            {
                string culture = Thread.CurrentThread.CurrentCulture.ToString();
                if (culture.Contains("ru"))
                {
                    return CurrentLanguage.Russian;
                }
                else
                {
                    return CurrentLanguage.English;
                }
            }
        }

        #region Addresses

        public static IEnumerable<Addresses> Addresseses
        {
            get { return Entities.Addresses; }
        }


        /// <summary>
        /// Получение адреса по ИД
        /// </summary>
        /// <param name="idAddress">ID</param>
        /// <returns>Адрес</returns>
        public static Addresses GetAddressById(int idAddress)
        {
            return Addresseses.FirstOrDefault(c => c.IdAddress == idAddress);
        }

        #endregion

        #region Settlements

        //public static List<Settlements> Settlements
        //{
        //    get { return Entities.Settlements.ToList(); }
        //}

        #endregion

        #region Dealers

        /// <summary>
        /// Дилеры
        /// </summary>
        public static IEnumerable<Customers> Dealers
        {
            get
            {
                List<Customers> result = new List<Customers>();

                foreach (var customer in Customers)
                {
                    if (customer.IsDealer)
                    {
                        result.Add(customer);
                    }
                }

                return result;
                // return Customers.Where(p => p.IsDealer == true);
            }
        }

        /// <summary>
        /// Поиск дилера по названию юридического лица
        /// </summary>
        /// <param name="dealerName">Название юридического лица дилера</param>
        /// <param name="exactName">Искать полное совпадение?</param>
        /// <returns>Найденный дилер</returns>
        public static Customers GetDealerByName(string dealerName, bool exactName = true)
        {
            Customers result = null;


            if (exactName)
            {
                foreach (var dealer in Dealers)
                {
                    if (dealer.LegalEntities.Any(legalEntity => legalEntity.Name == dealerName))
                    {
                        result = dealer;
                        break;
                    }
                }
            }
            else
            {
                foreach (var dealer in Dealers)
                {
                    foreach (var legalEntity in dealer.LegalEntities)
                    {
                        if (legalEntity.Name.Trim().ToUpper() == dealerName.Trim().ToUpper())
                        {
                            result = dealer;
                            break;
                        }
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Поиск дилера по названию юридического лица
        /// </summary>
        /// <param name="dealerName">Название юридического лица дилера</param>
        /// <param name="exactName">Искать полное совпадение?</param>
        /// <returns>Найденный дилер</returns>
        public static LegalEntities GetDealerLegalEntityByName(string dealerName, bool exactName = true)
        {
            LegalEntities result = null;


            if (exactName)
            {
                foreach (var dealer in Dealers)
                {
                    foreach (var legalEntity in dealer.LegalEntities)
                    {
                        if (legalEntity.Name == dealerName)
                        {
                            result = legalEntity;
                            break;
                        }
                    }
                }
            }
            else
            {
                foreach (var dealer in Dealers)
                {
                    foreach (var legalEntity in dealer.LegalEntities)
                    {
                        if (legalEntity.Name.Trim().ToUpper() == dealerName.Trim().ToUpper())
                        {
                            result = legalEntity;
                            break;
                        }
                    }
                }
            }

            return result;
        }

        #endregion

        #region Geometries

        /// <summary>
        /// Список геометрий
        /// </summary>
        public static ObjectSet<Geometries> Geometries
        {
            get { return Entities.Geometries; }
        }

        /// <summary>
        /// Только активные геометрии
        /// </summary>
        public static IQueryable<Geometries> GeometriesActive
        {
            get { return Geometries.Where(p => p.IsActive.Equals(true)); }
        }

        /// <summary>
        /// Получить геометрию по Id
        /// </summary>
        /// <param name="idGeometry">Id геометрии</param>
        /// <returns>Геометрия</returns>
        public static Geometries GetGeometrybyId(int idGeometry)
        {
            Geometries _result = null;

            foreach (Geometries geometry in Geometries)
            {
                if (geometry.IdGeometry == idGeometry)
                {
                    _result = geometry;
                    break;
                }
            }

            return _result;
        }

        /// <summary>
        /// Обновление геометрии
        /// </summary>
        /// <param name="geometry">Геометрия</param>
        /// <param name="userLogin">Логин пользователя, сделавшего изменение</param>
        public static void GeometriesUpdate(Geometries geometry, string userLogin)
        {
            if (geometry != null)
            {
                Geometries geometryUpdate = GetGeometrybyId(geometry.IdGeometry);
                if (geometryUpdate != null)
                {
                    geometryUpdate.Geometry = geometry.Geometry;
                    geometryUpdate.IsActive = geometry.IsActive;
                    geometryUpdate.IdUser = userLogin;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление геометрии
        /// </summary>
        /// <param name="geometry">Геометрия</param>
        public static void GeometriesInsert(Geometries geometry)
        {
            Entities.Geometries.AddObject(geometry);
            DB.Save();
        }

        /// <summary>
        /// Удаление геометрии
        /// </summary>
        /// <param name="geometry">Геометрия</param>
        public static void GeometriesDelete(Geometries geometry)
        {
            if (geometry != null)
            {
                Geometries geometryDel = GetGeometrybyId(geometry.IdGeometry);
                if (geometryDel != null)
                {
                    Geometries.DeleteObject(geometryDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Areas

        /// <summary>
        /// Список районов
        /// </summary>
        public static ObjectSet<Areas> Areas
        {
            get { return Entities.Areas; }
        }

        /// <summary>
        /// Только активные районы
        /// </summary>
        public static IQueryable<Areas> AreasActive
        {
            get { return Areas.Where(p => p.IsActive.Equals(true)); }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedAreasNames()
        {
            List<LocalizedListItem> result = null;
            foreach (Areas area in Areas)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = area.IdArea;
                listItem.ParentCollection = Areas;


                switch (CurrentLanguage)
                {
                    case CurrentLanguage.Russian:
                        listItem.LocaLizedString = area.NameRu;
                        break;
                    case CurrentLanguage.English:
                        listItem.LocaLizedString = area.NameEn;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить район по Id
        /// </summary>
        /// <param name="idArea">Id района</param>
        /// <returns>Район</returns>
        public static Areas GetAreabyId(int idArea)
        {
            Areas _result = null;
            foreach (Areas area in Areas)
            {
                if (area.IdArea == idArea)
                {
                    _result = area;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление района
        /// </summary>
        /// <param name="area">район</param>
        public static void AreasUpdate(Areas area)
        {
            if (area != null)
            {
                Areas areaUpdate = GetAreabyId(area.IdArea);
                if (areaUpdate != null)
                {
                    areaUpdate.IsActive = area.IsActive;
                    areaUpdate.IdRegion = area.IdRegion;
                    areaUpdate.NameEn = area.NameEn;
                    areaUpdate.NameRu = area.NameRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление района
        /// </summary>
        /// <param name="area">Район</param>
        public static void AreasInsert(Areas area)
        {
            Entities.Areas.AddObject(area);

            DB.Save();
        }

        /// <summary>
        /// Удаление района
        /// </summary>
        /// <param name="area">Район</param>
        public static void AreasDelete(Areas area)
        {
            if (area != null)
            {
                Areas areDel = GetAreabyId(area.IdArea);
                if (areDel != null)
                {
                    Areas.DeleteObject(areDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Colors

        /// <summary>
        /// Список цветов
        /// </summary>
        public static ObjectSet<Colors> Colors
        {
            get { return Entities.Colors; }
        }

        /// <summary>
        /// Только активные цвета
        /// </summary>
        public static IQueryable<Colors> ColorsActive
        {
            get { return Colors.Where(p => p.IsActive.Equals(true)); }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedColorsNames()
        {
            List<LocalizedListItem> result = null;
            foreach (Colors item in Colors)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdColor;
                listItem.ParentCollection = Colors;

                switch (CurrentLanguage)
                {
                    case CurrentLanguage.Russian:
                        listItem.LocaLizedString = item.NameRu;
                        break;
                    case CurrentLanguage.English:
                        listItem.LocaLizedString = item.NameEn;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить цвет по Id
        /// </summary>
        /// <param name="idColor">Id цвета</param>
        /// <returns>Цвет</returns>
        public static Colors GetColorbyId(int idColor)
        {
            Colors _result = null;
            foreach (Colors color in Colors)
            {
                if (color.IdColor == idColor)
                {
                    _result = color;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление цвета
        /// </summary>
        /// <param name="color">цвет</param>
        public static void ColorsUpdate(Colors color)
        {
            if (color != null)
            {
                Colors colorUpdate = GetColorbyId(color.IdColor);
                if (colorUpdate != null)
                {
                    colorUpdate.IsActive = color.IsActive;
                    colorUpdate.NameEn = color.NameEn;
                    colorUpdate.NameRu = color.NameRu;
                    colorUpdate.NameSAP = color.NameSAP;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление цвета
        /// </summary>
        /// <param name="color">Цвет</param>
        public static void ColorsInsert(Colors color)
        {
            Entities.Colors.AddObject(color);
            DB.Save();
        }

        /// <summary>
        /// Удаление цвета
        /// </summary>
        /// <param name="color">цвет</param>
        public static void ColorsDelete(Colors color)
        {
            if (color != null)
            {
                Colors colorDel = GetColorbyId(color.IdColor);
                if (colorDel != null)
                {
                    Colors.DeleteObject(colorDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Countries

        /// <summary>
        /// Список стран
        /// </summary>
        public static ObjectSet<Countries> Countries
        {
            get { return Entities.Countries; }
        }

        /// <summary>
        /// Активные страны
        /// </summary>
        public static IQueryable<Countries> CountriesActive
        {
            get
            {
                return
                    Countries.Where(p => p.IsActive).Where(q => q.Organisations.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedCountriesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (Countries item in Countries)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdCountry;
                listItem.ParentCollection = Countries;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.CountryRu;
                }
                else
                {
                    listItem.LocaLizedString = item.CountryEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedCountriesNames()
        {
            List<LocalizedListItem> result = null;
            foreach (Countries item in Countries)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdCountry;
                listItem.ParentCollection = Countries;
                switch (CurrentLanguage)
                {
                    case CurrentLanguage.Russian:
                        listItem.LocaLizedString = item.CountryRu;
                        break;
                    case CurrentLanguage.English:
                        listItem.LocaLizedString = item.CountryEn;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                if (!result.Contains(listItem)) result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить страну по Id
        /// </summary>
        /// <param name="idCountry">Id страну</param>
        /// <returns>Страна</returns>
        public static Countries GetCountrybyId(int idCountry)
        {
            Countries _result = null;
            foreach (Countries country in Countries)
            {
                if (country.IdCountry == idCountry)
                {
                    _result = country;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление страны
        /// </summary>
        /// <param name="сountry">страна</param>
        public static void CountriesUpdate(Countries сountry)
        {
            if (сountry != null)
            {
                Countries сountryUpdate = GetCountrybyId(сountry.IdCountry);
                if (сountryUpdate != null)
                {
                    сountryUpdate.IsActive = сountry.IsActive;
                    сountryUpdate.IdOrganisation = сountry.IdOrganisation;
                    сountryUpdate.CountryEn = сountry.CountryEn;
                    сountryUpdate.CountryRu = сountry.CountryRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление страны
        /// </summary>
        /// <param name="сountry">Страна</param>
        public static void CountriesInsert(Countries сountry)
        {
            Entities.Countries.AddObject(сountry);
            DB.Save();
        }

        /// <summary>
        /// Удаление страны
        /// </summary>
        /// <param name="сountry">Страна</param>
        public static void CountriesDelete(Countries сountry)
        {
            if (сountry != null)
            {
                Countries сountryDel = GetCountrybyId(сountry.IdCountry);
                if (сountryDel != null)
                {
                    Countries.DeleteObject(сountryDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region CustomerClassifications

        /// <summary>
        /// Список классификаций клиента
        /// </summary>
        public static ObjectSet<CustomerClassifications> CustomerClassifications
        {
            get { return Entities.CustomerClassifications; }
        }

        /// <summary>
        /// Только активные классификации клиента
        /// </summary>
        public static IQueryable<CustomerClassifications> CustomerClassificationsActive
        {
            get { return CustomerClassifications.Where(p => p.IsActive.Equals(true)); }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedCustomerClassificationsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (CustomerClassifications item in CustomerClassifications)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdCustomerClassification;
                listItem.ParentCollection = CustomerClassifications;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить классификацию клиента по Id
        /// </summary>
        /// <param name="idCustomerClassification">Id классификации лиента</param>
        /// <returns>Классификация клиента</returns>
        public static CustomerClassifications GetCustomerClassificationbyId(int idCustomerClassification)
        {
            CustomerClassifications _result = null;
            foreach (CustomerClassifications сlassification in CustomerClassifications)
            {
                if (сlassification.IdCustomerClassification == idCustomerClassification)
                {
                    _result = сlassification;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление классификации клиента
        /// </summary>
        /// <param name="сlassification">Классификация клиента</param>
        public static void CustomerClassificationsUpdate(CustomerClassifications сlassification)
        {
            if (сlassification != null)
            {
                CustomerClassifications сlassificationUpdate =
                    GetCustomerClassificationbyId(сlassification.IdCustomerClassification);
                if (сlassificationUpdate != null)
                {
                    сlassificationUpdate.IsActive = сlassification.IsActive;
                    сlassificationUpdate.MaxRevenue = сlassification.MaxRevenue;
                    сlassificationUpdate.MinRevenue = сlassification.MinRevenue;
                    сlassificationUpdate.NameEn = сlassification.NameEn;
                    сlassificationUpdate.NameRu = сlassification.NameRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление классификации клиента
        /// </summary>
        /// <param name="сlassification">Классификация клиента</param>
        public static void CustomerClassificationsInsert(CustomerClassifications сlassification)
        {
            Entities.CustomerClassifications.AddObject(сlassification);
            DB.Save();
        }

        /// <summary>
        /// Удаление классификации клиента
        /// </summary>
        /// <param name="сlassification">Классификация клиента</param>
        public static void CustomerClassificationsDelete(CustomerClassifications сlassification)
        {
            if (сlassification != null)
            {
                CustomerClassifications сlassificationDel =
                    GetCustomerClassificationbyId(сlassification.IdCustomerClassification);
                if (сlassificationDel != null)
                {
                    CustomerClassifications.DeleteObject(сlassificationDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Customers

        /// <summary>
        /// Список клиентов
        /// </summary>
        public static ObjectSet<Customers> Customers
        {
            get { return Entities.Customers; }
        }

        /// <summary>
        /// Только активные клиенты
        /// </summary>
        public static List<Customers> CustomersActive
        {
            get
            {
                List<Customers> result = new List<Customers>();

                foreach (var item in Customers)
                {
                    result.Add(item);
                }
                return result;
                //return Customers.Where(p => p.IsActive.Equals(true)).ToList();
            }
        }

        /// <summary>
        /// Получить клиента Id
        /// </summary>
        /// <param name="idCustomer">Id клиента</param>
        /// <returns>Клиент</returns>
        public static Customers GetCustomerById(int idCustomer)
        {
            foreach (Customers сustomer in Customers)
            {
                if (сustomer.IdCustomer == idCustomer) return сustomer;
            }
            return null;
        }

        /// <summary>
        /// Получение списка клиентов по клиентскому номеру
        /// </summary>
        /// <param name="seqNumber">Клиентский номер</param>
        /// <returns>Список клиентов</returns>
        public static Customers GetCustomerBySequentalNumber(int seqNumber)
        {
            foreach (var item in Customers)
            {
                if (item.SequentialNumber == seqNumber) return item;
            }
            return null;
        }

        /// <summary>
        /// Получение клиента по номеру SAP
        /// </summary>
        /// <param name="sapNumber"></param>
        /// <returns>Список Юр лиц</returns>
        public static LegalEntities GetLegalEntityBySapNumber(int sapNumber)
        {
            foreach (var legalEntity in LegalEntities)
            {
                if (legalEntity.NumberInSAP == sapNumber)
                {

                    return legalEntity;
                }
            }
            return null;
        }

        /// <summary>
        /// Обновление клиента
        /// </summary>
        /// <param name="customer">клиент</param>
        /// <param name="userLogin">Логин пользователя, который делает изменения</param>
        public static void CustomersUpdate(Customers customer, string userLogin)
        {
            if (customer != null)
            {
                Customers customerUpdate = GetCustomerBySequentalNumber(customer.SequentialNumber);
                if (customerUpdate != null)
                {
                    if (customer.IdprofineRegion != null)
                    {
                        customerUpdate.IdprofineRegion = customer.IdprofineRegion;
                    }

                    if (customer.NumberInSAP != null)
                    {
                        customerUpdate.NumberInSAP = customer.NumberInSAP;
                    }
                    if (!string.IsNullOrEmpty(customer.Comments))
                    {
                        customerUpdate.Comments = customer.Comments;
                    }

                    if (customer.DateStartProfineRUS > DateTime.MinValue)
                    {
                        customerUpdate.DateStartProfineRUS = customer.DateStartProfineRUS;
                    }


                    if (!String.IsNullOrEmpty(customer.Name))
                    {
                        customerUpdate.Name = customer.Name;
                    }
                    //customerUpdate.SequentialNumber = customer.SequentialNumber;
                    customerUpdate.IdUser = userLogin;

                    if (customer.IdCustomerClassificationsByBusiness != null)
                    {
                        customerUpdate.IdCustomerClassificationsByBusiness = customer.IdCustomerClassificationsByBusiness;
                    }
                    if (customer.IdCustomerClassificationsProfine != null)
                    {
                        customerUpdate.IdCustomerClassificationsProfine = customer.IdCustomerClassificationsProfine;
                    }
                    if (customer.IdCustomerClassificationsTurnover != null)
                    {
                        customerUpdate.IdCustomerClassificationsTurnover = customer.IdCustomerClassificationsTurnover;
                    }

                    if (customer.IdManager != null)
                    {
                        customerUpdate.IdManager = customer.IdManager;
                    }

                    //   customerUpdate.IsActive = customer.IsActive;
                    customerUpdate.SaveTime = DateTime.Now;


                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление клиента
        /// </summary>
        /// <param name="customer">клиент</param>
        public static void CustomersInsert(Customers customer)
        {
            Entities.Customers.AddObject(customer);
            DB.Save();
        }

        /// <summary>
        /// Добавление клиента в базу
        /// </summary>
        /// <param name="customer">Клиент</param>
        /// <param name="userLogin">Пользователь, который вносит изменение</param>
        /// <returns>Ид клиента</returns>
        //public static int CustomersInsert(Customers customer, string userLogin)
        //{
        //    customer.IdUser = userLogin;
        //    customer.SaveTime = DateTime.Now;
        //    customer.IsActive = true;
        //    int num = MaxCustomerSequentalNumber + 1;
        //    customer.SequentialNumber = num;

        //    Entities.Customers.AddObject(customer);
        //    DB.Save();

        //    var cust = GetCustomerBySequentalNumber(num);

        //    var le = new LegalEntities { Name = cust.Name };
        //    cust.AddLegalEntity(le, userLogin);

        //    return cust.IdCustomer;
        //}


        /// <summary>
        /// Максимальный порядковый номер клиента
        /// </summary>
        public static int MaxCustomerSequentalNumber
        {
            get
            {
                return Enumerable.Concat(Customers.Select(customer => customer.SequentialNumber), new[] { 0 }).Max();
            }
        }

        /// <summary>
        /// Удаление клиента
        /// </summary>
        /// <param name="customer">клиент</param>
        public static void CustomersDelete(Customers customer)
        {
            if (customer != null)
            {
                Customers customerDel = GetCustomerById(customer.IdCustomer);
                if (customerDel != null)
                {
                    Customers.DeleteObject(customerDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region CustomersEquipments

        /// <summary>
        /// Все инструменты всех клиентов
        /// </summary>
        public static ObjectSet<CustomersEquipments> CustomersEquipments
        {
            get { return Entities.CustomersEquipments; }
        }

        public static void CustomersEquipmentInsert(CustomersEquipments equipments, string idUser)
        {
            CustomersEquipments newCustEquip = new CustomersEquipments();

            newCustEquip.IdUser = idUser;
            newCustEquip.IdEquipment = equipments.IdEquipment;
            newCustEquip.IdCustomer = equipments.IdCustomer;
            newCustEquip.IssueDate = equipments.IssueDate;
            newCustEquip.EquipmentCount = equipments.EquipmentCount;

            //if(GetCustomersEquipmentsbyIdCustomerAndIdEquipment( newCustEquip.IdCustomer, newCustEquip.IdEquipment)==null)
            //{
            Entities.CustomersEquipments.AddObject(newCustEquip);
            DB.Save();
            //   }



        }


        /// <summary>
        /// Поиск оборудования клиента
        /// </summary>
        /// <param name="idCustomer">Идентификатор клиента</param>
        /// <param name="idEquipment">Идентификатор оборудования</param>
        /// <returns>Связка клиент-оборудование</returns>
        public static CustomersEquipments GetCustomersEquipmentsbyIdCustomerAndIdEquipment(int idCustomer, int idEquipment)
        {
            return CustomersEquipments.FirstOrDefault(p => p.IdCustomer == idCustomer && p.IdEquipment == idEquipment);
        }

        #endregion

        #region Districts

        /// <summary>
        /// Список областей
        /// </summary>
        public static ObjectSet<Districts> Districts
        {
            get { return Entities.Districts; }
        }

        /// <summary>
        /// Активные инструменты
        /// </summary>
        public static IQueryable<Districts> DistrictsActive
        {
            get
            {
                return
                    Districts.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedDistrictsShortNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (Districts item in Districts)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdDistrict;
                listItem.ParentCollection = Districts;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameShortRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameShortEn;
                }
                result.Add(listItem);
            }
            return result;
        }




        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedDistrictsShortNames()
        {
            List<LocalizedListItem> result = null;
            foreach (Districts item in Districts)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdDistrict;
                listItem.ParentCollection = Districts;
                switch (CurrentLanguage)
                {
                    case CurrentLanguage.Russian:
                        listItem.LocaLizedString = item.NameShortRu;
                        break;
                    case CurrentLanguage.English:
                        listItem.LocaLizedString = item.NameShortEn;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                result.Add(listItem);
            }
            return result;
        }


        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedDistrictsNames()
        {
            List<LocalizedListItem> result = null;
            foreach (Districts item in Districts)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdDistrict;
                listItem.ParentCollection = Districts;
                switch (CurrentLanguage)
                {
                    case CurrentLanguage.Russian:
                        listItem.LocaLizedString = item.NameRu;
                        break;
                    case CurrentLanguage.English:
                        listItem.LocaLizedString = item.NameEn;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить область по Id
        /// </summary>
        /// <param name="idDistrict">Id области</param>
        /// <returns>Область</returns>
        public static Districts GetDistrictbyId(int idDistrict)
        {
            Districts _result = null;
            foreach (Districts district in Districts)
            {
                if (district.IdDistrict == idDistrict)
                {
                    _result = district;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление области
        /// </summary>
        /// <param name="district">область</param>
        public static void DistrictsUpdate(Districts district)
        {
            if (district != null)
            {
                Districts districtUpdate = GetDistrictbyId(district.IdDistrict);
                if (districtUpdate != null)
                {
                    districtUpdate.IsActive = district.IsActive;
                    districtUpdate.IdCountry = district.IdCountry;
                    districtUpdate.NameEn = district.NameEn;
                    districtUpdate.NameRu = district.NameRu;
                    districtUpdate.NameShortEn = district.NameShortEn;
                    districtUpdate.NameShortRu = district.NameShortRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление области
        /// </summary>
        /// <param name="district">Область</param>
        public static void DistrictsInsert(Districts district)
        {
            Entities.Districts.AddObject(district);
            DB.Save();
        }

        /// <summary>
        /// Удаление района
        /// </summary>
        /// <param name="district">Район</param>
        public static void DistrictsDelete(Districts district)
        {
            if (district != null)
            {
                Districts districtDel = GetDistrictbyId(district.IdDistrict);
                if (districtDel != null)
                {
                    Districts.DeleteObject(districtDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Organisations

        /// <summary>
        /// Список организаций
        /// </summary>
        public static ObjectSet<Organisations> Organisations
        {
            get { return Entities.Organisations; }
        }

        /// <summary>
        /// Активные организации
        /// </summary>
        public static IQueryable<Organisations> OrganisationsActive
        {
            get
            {
                return
                    Organisations.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedOrganisationsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (Organisations item in Organisations)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdOrganisation;
                listItem.ParentCollection = Organisations;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.OrganisationRu;
                }
                else
                {
                    listItem.LocaLizedString = item.OrganisationEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить организацию по Id
        /// </summary>
        /// <param name="idOrganisation">Id организации</param>
        /// <returns>Организация</returns>
        public static Organisations GetOrganisationbyId(int idOrganisation)
        {
            Organisations _result = null;
            foreach (Organisations organisation in Organisations)
            {
                if (organisation.IdOrganisation == idOrganisation)
                {
                    _result = organisation;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление организации
        /// </summary>
        /// <param name="organisation">организация</param>
        public static void OrganisationsUpdate(Organisations organisation)
        {
            if (organisation != null)
            {
                Organisations organisationUpdate = GetOrganisationbyId(organisation.IdOrganisation);
                if (organisationUpdate != null)
                {
                    organisationUpdate.IsActive = organisation.IsActive;
                    organisationUpdate.OrganisationEn = organisation.OrganisationEn;
                    organisationUpdate.OrganisationRu = organisation.OrganisationRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление организации
        /// </summary>
        /// <param name="organisation">Организация</param>
        public static void OrganisationsInsert(Organisations organisation)
        {
            Entities.Organisations.AddObject(organisation);
            DB.Save();
        }

        /// <summary>
        /// Удаление организации
        /// </summary>
        /// <param name="organisation">Организация</param>
        public static void OrganisationsDelete(Organisations organisation)
        {
            if (organisation != null)
            {
                Organisations organisationDel = GetOrganisationbyId(organisation.IdOrganisation);
                if (organisationDel != null)
                {
                    Organisations.DeleteObject(organisationDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region OwnershipPatterns

        /// <summary>
        /// Список форм собственности
        /// </summary>
        public static ObjectSet<OwnershipPatterns> OwnershipPatterns
        {
            get { return Entities.OwnershipPatterns; }
        }

        /// <summary>
        /// Активные формы собственности
        /// </summary>
        public static IQueryable<OwnershipPatterns> OwnershipPatternsActive
        {
            get
            {
                return
                    OwnershipPatterns.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedOwnershipPatternsShortNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (OwnershipPatterns item in OwnershipPatterns)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdOwnershipPattern;
                listItem.ParentCollection = OwnershipPatterns;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameShortRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameShortEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить форму собственности по Id
        /// </summary>
        /// <param name="idOwnershipPattern">Id формы собственности</param>
        /// <returns>Форма собственности</returns>
        public static OwnershipPatterns GetOwnershipPatternbyId(int idOwnershipPattern)
        {
            OwnershipPatterns _result = null;
            foreach (OwnershipPatterns pattern in OwnershipPatterns)
            {
                if (pattern.IdOwnershipPattern == idOwnershipPattern)
                {
                    _result = pattern;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление формы собственности
        /// </summary>
        /// <param name="pattern">Форма собственности</param>
        public static void OwnershipPatternsUpdate(OwnershipPatterns pattern)
        {
            if (pattern != null)
            {
                OwnershipPatterns patternUpdate = GetOwnershipPatternbyId(pattern.IdOwnershipPattern);
                if (patternUpdate != null)
                {
                    patternUpdate.IsActive = pattern.IsActive;
                    patternUpdate.NameEn = pattern.NameEn;
                    patternUpdate.NameRu = pattern.NameRu;
                    patternUpdate.NameShortEn = pattern.NameShortEn;
                    patternUpdate.NameShortRu = pattern.NameShortRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление формы собственности
        /// </summary>
        /// <param name="pattern">Форма собственности</param>
        public static void OwnershipPatternsInsert(OwnershipPatterns pattern)
        {
            Entities.OwnershipPatterns.AddObject(pattern);
            DB.Save();
        }

        /// <summary>
        /// Удаление формы собственности
        /// </summary>
        /// <param name="pattern">Форма собственности</param>
        public static void OwnershipPatternsDelete(OwnershipPatterns pattern)
        {
            if (pattern != null)
            {
                OwnershipPatterns patternDel = GetOwnershipPatternbyId(pattern.IdOwnershipPattern);
                if (patternDel != null)
                {
                    OwnershipPatterns.DeleteObject(patternDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region ProductGroups

        /// <summary>
        /// Список групп продуктов
        /// </summary>
        public static ObjectSet<ProductGroups> ProductGroups
        {
            get { return Entities.ProductGroups; }
        }

        /// <summary>
        /// Активные группы продуктов
        /// </summary>
        public static IQueryable<ProductGroups> ProductGroupsActive
        {
            get
            {
                return
                    ProductGroups.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedProductGroupsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (ProductGroups item in ProductGroups)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdProductGroup;
                listItem.ParentCollection = ProductGroups;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.GroupNameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.GroupNameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить группу продуктов по Id
        /// </summary>
        /// <param name="idProductGroup">Id группы продуктов</param>
        /// <returns>Группа продуктов</returns>
        public static ProductGroups GetProductGroupbyId(int idProductGroup)
        {
            ProductGroups _result = null;
            foreach (ProductGroups group in ProductGroups)
            {
                if (group.IdProductGroup == idProductGroup)
                {
                    _result = group;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление группы продуктов
        /// </summary>
        /// <param name="group">Группа продуктов</param>
        public static void ProductGroupsUpdate(ProductGroups group)
        {
            if (group != null)
            {
                ProductGroups groupUpdate = GetProductGroupbyId(group.IdProductGroup);
                if (groupUpdate != null)
                {
                    groupUpdate.IsActive = group.IsActive;
                    groupUpdate.DescriptionEn = group.DescriptionEn;
                    groupUpdate.DescriptionGer = group.DescriptionGer;
                    groupUpdate.DescriptionRu = group.DescriptionRu;
                    groupUpdate.GroupNameEn = group.GroupNameEn;
                    groupUpdate.GroupNameRu = group.GroupNameRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление группы продуктов
        /// </summary>
        /// <param name="group">Группа продуктов</param>
        public static void ProductGroupsInsert(ProductGroups group)
        {
            Entities.ProductGroups.AddObject(group);
            DB.Save();
        }

        /// <summary>
        /// Удаление группы продуктов
        /// </summary>
        /// <param name="group">Группа продуктов</param>
        public static void ProductGroupsDelete(ProductGroups group)
        {
            if (group != null)
            {
                ProductGroups groupDel = GetProductGroupbyId(group.IdProductGroup);
                if (groupDel != null)
                {
                    ProductGroups.DeleteObject(groupDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Products

        /// <summary>
        /// Список продуктов
        /// </summary>
        public static ObjectSet<Products> Products
        {
            get { return Entities.Products; }
        }

        /// <summary>
        /// Активные продукты
        /// </summary>
        //public static IQueryable<Products> ProductsActive
        //{
        //    get
        //    {
        //        return
        //            Products.Where(a => a.IsActive).Where(b => b.ProductGroups.IsActive).Where(
        //                c => c.ProfileGeometry.IsActive).Where(d => d.PackingColor.IsActive).Where(
        //                    e => e.OutsideColor.IsActive).Where(
        //                        f => f.InsideColor.IsActive);
        //    }
        //}

        /// <summary>
        /// Получить продукт по Id
        /// </summary>
        /// <param name="idProduct">Id продукта</param>
        /// <returns>Продукт</returns>
        public static Products GetProductbyId(int idProduct)
        {
            Products _result = null;
            foreach (Products product in Products)
            {
                if (product.IdProduct == idProduct)
                {
                    _result = product;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Получить продукт по SAP номеру материала
        /// </summary>
        /// <param name="sapMaterialNumber"></param>
        /// <returns>Продукт</returns>
        public static Products GetProductbySapMaterialNumber(string sapMaterialNumber)
        {
            Products _result = null;
            foreach (Products product in Products)
            {
                if (product.SAPMaterialNumber == sapMaterialNumber)
                {
                    _result = product;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление продукта
        /// </summary>
        /// <param name="product">Продукт</param>
        public static void ProductsUpdate(Products product)
        {
            if (product != null)
            {
                Products productUpdate = GetProductbyId(product.IdProduct);
                if (productUpdate != null)
                {
                    productUpdate.IsActive = product.IsActive;
                    productUpdate.SAPMaterialNumber = product.SAPMaterialNumber;
                    productUpdate.MountingDepth = product.MountingDepth;
                    productUpdate.IdProductGroup = product.IdProductGroup;
                    productUpdate.IdProfileGeometry = product.IdProfileGeometry;
                    productUpdate.IdPackingColor = product.IdPackingColor;
                    productUpdate.IdOutsideColor = product.IdOutsideColor;
                    productUpdate.IdInsideColor = product.IdInsideColor;
                    productUpdate.ProfileLength = product.ProfileLength;
                    productUpdate.Aricle = product.Aricle;
                    productUpdate.IdInstrumentGeometry = product.IdInstrumentGeometry;
                    productUpdate.ArticleLong = product.ArticleLong;
                    productUpdate.Weight = product.Weight;
                    productUpdate.StabProPallette = product.StabProPallette;
                    productUpdate.IdProductSystem = product.IdProductSystem;
                    productUpdate.IdProductSystemName = product.IdProductSystemName;
                    productUpdate.IdProductMark = product.IdProductMark;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление продукта
        /// </summary>
        /// <param name="product">Продукт</param>
        public static void ProductsInsert(Products product)
        {
            Entities.Products.AddObject(product);
            DB.Save();
        }

        /// <summary>
        /// Удаление продукта
        /// </summary>
        /// <param name="product">Продукт</param>
        public static void ProductsDelete(Products product)
        {
            if (product != null)
            {
                Products productDel = GetProductbyId(product.IdProduct);
                if (productDel != null)
                {
                    Products.DeleteObject(productDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region profineRegions

        /// <summary>
        /// Список регионов профайн
        /// </summary>
        public static ObjectSet<profineRegions> profineRegions
        {
            get { return Entities.profineRegions; }
        }

        /// <summary>
        /// Активные регионы профайн
        /// </summary>
        public static IQueryable<profineRegions> profineRegionsActive
        {
            get
            {
                return
                    profineRegions.Where(p => p.IsActive).Where(q => q.Countries.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedProfineRegionsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (profineRegions item in profineRegions)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdProfineRegion;
                listItem.ParentCollection = profineRegions;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить регион профайн по Id
        /// </summary>
        /// <param name="idprofineRegions">Id региона профайн</param>
        /// <returns>Ргион профайн</returns>
        public static profineRegions GetprofineRegionbyId(int idprofineRegions)
        {
            profineRegions _result = null;
            foreach (profineRegions reg in profineRegions)
            {
                if (reg.IdProfineRegion == idprofineRegions)
                {
                    _result = reg;
                    break;
                }
            }
            return _result;
        }

        public static profineRegions GetprofineRegionbyNameRu(string profineRegionNameRu)
        {
            // profineRegions _result = null;
            foreach (var reg in profineRegions.Where(reg => reg.NameRu == profineRegionNameRu))
            {
                return reg;
            }

            return null;
        }

        /// <summary>
        /// Обновление регион профайн
        /// </summary>
        /// <param name="reg">ргион профайн</param>
        public static void profineRegionsUpdate(profineRegions reg)
        {
            if (reg != null)
            {
                profineRegions regUpdate = GetprofineRegionbyId(reg.IdProfineRegion);
                if (regUpdate != null)
                {
                    regUpdate.IsActive = reg.IsActive;
                    regUpdate.IdCountry = reg.IdCountry;
                    regUpdate.NameEn = reg.NameEn;
                    regUpdate.NameRu = reg.NameRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление региона профайн
        /// </summary>
        /// <param name="reg">ргион профайн</param>
        public static void profineRegionsInsert(profineRegions reg)
        {
            Entities.profineRegions.AddObject(reg);
            DB.Save();
        }

        /// <summary>
        /// Удаление региона профайн
        /// </summary>
        /// <param name="reg">ргион профайн</param>
        public static void profineRegionsDelete(profineRegions reg)
        {
            if (reg != null)
            {
                profineRegions regDel = GetprofineRegionbyId(reg.IdProfineRegion);
                if (regDel != null)
                {
                    profineRegions.DeleteObject(regDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Regions

        /// <summary>
        /// Список регионов
        /// </summary>
        public static ObjectSet<Regions> Regions
        {
            get { return Entities.Regions; }
        }

        /// <summary>
        /// Активные регионы
        /// </summary>
        public static IQueryable<Regions> RegionsActive
        {
            get
            {
                return
                    Regions.Where(a => a.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedRegionsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (Regions item in Regions)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdRegion;
                listItem.ParentCollection = Regions;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>

        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedRegionsNames()
        {
            List<LocalizedListItem> result = null;
            foreach (Regions item in Regions)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdRegion;
                listItem.ParentCollection = Regions;
                switch (CurrentLanguage)
                {
                    case CurrentLanguage.Russian:
                        listItem.LocaLizedString = item.NameRu;
                        break;
                    case CurrentLanguage.English:
                        listItem.LocaLizedString = item.NameEn;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                result.Add(listItem);
            }
            return result;
        }


        /// <summary>
        /// Получить регион по Id
        /// </summary>
        /// <param name="idRegion">Id региона</param>
        /// <returns>регион</returns>
        public static Regions GetRegionbyId(int idRegion)
        {
            Regions _result = null;
            foreach (Regions reg in Regions)
            {
                if (reg.IdRegion == idRegion)
                {
                    _result = reg;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление региона
        /// </summary>
        /// <param name="reg">регион</param>
        public static void RegionsUpdate(Regions reg)
        {
            if (reg != null)
            {
                Regions regUpdate = GetRegionbyId(reg.IdRegion);
                if (regUpdate != null)
                {
                    regUpdate.IsActive = reg.IsActive;
                    regUpdate.NameRu = reg.NameRu;
                    regUpdate.NameEn = reg.NameEn;
                    regUpdate.IdDistrict = reg.IdDistrict;
                    regUpdate.IdProfineRegion = reg.IdProfineRegion;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление региона
        /// </summary>
        /// <param name="reg">регион</param>
        public static void RegionsInsert(Regions reg)
        {
            Entities.Regions.AddObject(reg);
            DB.Save();
        }

        /// <summary>
        /// Удаление региона
        /// </summary>
        /// <param name="reg">регион</param>
        public static void RegionsDelete(Regions reg)
        {
            if (reg != null)
            {
                Regions regDel = GetRegionbyId(reg.IdRegion);
                if (regDel != null)
                {
                    Regions.DeleteObject(regDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Settlements

        /// <summary>
        /// Список населенных пунктов
        /// </summary>
        public static IEnumerable<Settlements> Settlements
        {
            get
            {
                //List<Settlements> result = new List<Settlements>();
                //for (int i = 1; i < 1000; i++)
                //{
                //    result.Add(Entities.Settlements.Single(p=>p.IdSettlement==i));
                //}
                return Entities.Settlements;
            }
        }

        /// <summary>
        /// Активные населенные пункты
        /// </summary>
        public static IEnumerable<Settlements> SettlementsActive
        {
            get
            {
                return
                    Settlements.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedSettlementsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (Settlements item in Settlements)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdSettlement;
                listItem.ParentCollection = Settlements;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedSettlementsNames()
        {
            List<LocalizedListItem> result = null;
            foreach (Settlements item in Settlements)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdSettlement;
                listItem.ParentCollection = Settlements;
                switch (CurrentLanguage)
                {
                    case CurrentLanguage.Russian:
                        listItem.LocaLizedString = item.NameRu;
                        break;
                    case CurrentLanguage.English:
                        listItem.LocaLizedString = item.NameEn;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                result.Add(listItem);
            }
            return result;
        }


        /// <summary>
        /// Получить населенный пункт по Id
        /// </summary>
        /// <param name="idSettlement">Id населенного пункта</param>
        /// <returns>населенный пункт</returns>
        public static Settlements GetSettlementbyId(int idSettlement)
        {
            return Settlements.FirstOrDefault(p => p.IdSettlement == idSettlement);
        }

        /// <summary>
        /// Обновление населенного пункта
        /// </summary>
        /// <param name="settlement">населенный пункт</param>
        public static void SettlementsUpdate(Settlements settlement)
        {
            if (settlement != null)
            {
                Settlements settlementUpdate = GetSettlementbyId(settlement.IdSettlement);
                if (settlementUpdate != null)
                {
                    settlementUpdate.IsActive = settlement.IsActive;
                    settlementUpdate.NameEn = settlement.NameEn;
                    settlementUpdate.NameRu = settlement.NameRu;
                    settlementUpdate.IdArea = settlement.IdArea;
                    settlementUpdate.IdRegion = settlement.IdRegion;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление населенного пункта
        /// </summary>
        /// <param name="settlement">населенный пункт</param>
        public static void SettlementsInsert(Settlements settlement)
        {
            Entities.Settlements.AddObject(settlement);
            DB.Save();
        }

        /// <summary>
        /// Удаление населенного пункта
        /// </summary>
        /// <param name="settlement">населенный пункт</param>
        public static void SettlementsDelete(Settlements settlement)
        {
            if (settlement != null)
            {
                Settlements settlementDel = GetSettlementbyId(settlement.IdSettlement);
                if (settlementDel != null)
                {
                    Entities.Settlements.DeleteObject(settlementDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region ProductVendors

        /// <summary>
        /// Список производителей продуктов
        /// </summary>
        public static ObjectSet<ProductVendors> ProductVendors
        {
            get { return Entities.ProductVendors; }
        }

        /// <summary>
        /// Активные производители продуктов
        /// </summary>
        public static IQueryable<ProductVendors> ProductVendorsActive
        {
            get
            {
                return
                    ProductVendors.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedProductVendorsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (ProductVendors item in ProductVendors)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdProductVendor;
                listItem.ParentCollection = ProductVendors;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.ProductVendorRu;
                }
                else
                {
                    listItem.LocaLizedString = item.ProductVendorEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить производителя продуктов по Id
        /// </summary>
        /// <param name="idProductVendor">Id производителя продуктов</param>
        /// <returns>производитель продуктов</returns>
        public static ProductVendors GetProductVendorbyId(int idProductVendor)
        {
            ProductVendors _result = null;
            foreach (ProductVendors productVendor in ProductVendors)
            {
                if (productVendor.IdProductVendor == idProductVendor)
                {
                    _result = productVendor;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление производителей продуктов
        /// </summary>
        /// <param name="productVendor">производитель продуктов</param>
        public static void ProductVendorsUpdate(ProductVendors productVendor)
        {
            if (productVendor != null)
            {
                ProductVendors productVendorUpdate = GetProductVendorbyId(productVendor.IdProductVendor);
                if (productVendorUpdate != null)
                {
                    productVendorUpdate.IsActive = productVendor.IsActive;
                    productVendorUpdate.ProductVendorEn = productVendor.ProductVendorEn;
                    productVendorUpdate.ProductVendorRu = productVendor.ProductVendorRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление производителей продуктов
        /// </summary>
        /// <param name="productVendor">производитель продуктов</param>
        public static void ProductVendorsInsert(ProductVendors productVendor)
        {
            Entities.ProductVendors.AddObject(productVendor);
            DB.Save();
        }

        /// <summary>
        /// Удаление производителей продуктов
        /// </summary>
        /// <param name="productVendor">производитель продуктов</param>
        public static void ProductVendorsDelete(ProductVendors productVendor)
        {
            if (productVendor != null)
            {
                ProductVendors productVendorDel = GetProductVendorbyId(productVendor.IdProductVendor);
                if (productVendorDel != null)
                {
                    ProductVendors.DeleteObject(productVendorDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region ProductSystems

        /// <summary>
        /// Список систем продуктов
        /// </summary>
        public static ObjectSet<ProductSystems> ProductSystems
        {
            get { return Entities.ProductSystems; }
        }

        /// <summary>
        /// Активные системы продуктов
        /// </summary>
        public static IQueryable<ProductSystems> ProductSystemsActive
        {
            get
            {
                return
                    ProductSystems.Where(p => p.IsActive == true);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedProductSystemsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (ProductSystems item in ProductSystems)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdProductSystem;
                listItem.ParentCollection = ProductSystems;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.ProductSystemRu;
                }
                else
                {
                    listItem.LocaLizedString = item.ProductSystemEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить систему продуктов по Id
        /// </summary>
        /// <param name="idProductSystem">Id системы продуктов</param>
        /// <returns>система продуктов</returns>
        public static ProductSystems GetProductSystembyId(int idProductSystem)
        {
            ProductSystems _result = null;
            foreach (ProductSystems productSystem in ProductSystems)
            {
                if (productSystem.IdProductSystem == idProductSystem)
                {
                    _result = productSystem;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление системы продукта
        /// </summary>
        /// <param name="productSystemItem">система продукта</param>
        public static void ProductSystemsUpdate(ProductSystems productSystemItem)
        {
            if (productSystemItem != null)
            {
                ProductSystems productSystemUpdate = GetProductSystembyId(productSystemItem.IdProductSystem);
                if (productSystemUpdate != null)
                {
                    productSystemUpdate.IsActive = productSystemItem.IsActive;
                    productSystemUpdate.ProductSystemDe = productSystemItem.ProductSystemDe;
                    productSystemUpdate.ProductSystemEn = productSystemItem.ProductSystemEn;
                    productSystemUpdate.ProductSystemRu = productSystemItem.ProductSystemRu;
                    productSystemUpdate.ProductSystemSAP = productSystemItem.ProductSystemSAP;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление системы продукта
        /// </summary>
        /// <param name="productSystemItem">система продукта</param>
        public static void ProductSystemsInsert(ProductSystems productSystemItem)
        {
            Entities.ProductSystems.AddObject(productSystemItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление населенного пункта
        /// </summary>
        /// <param name="productSystemItem">населенный пункт</param>
        public static void ProductSystemsDelete(ProductSystems productSystemItem)
        {
            if (productSystemItem != null)
            {
                ProductSystems productSystemDel = GetProductSystembyId(productSystemItem.IdProductSystem);
                if (productSystemDel != null)
                {
                    ProductSystems.DeleteObject(productSystemDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region ProductMarks

        /// <summary>
        /// Список марок продуктов
        /// </summary>
        public static ObjectSet<ProductMarks> ProductMarks
        {
            get { return Entities.ProductMarks; }
        }

        /// <summary>
        /// Активные марки продуктов
        /// </summary>
        public static IQueryable<ProductMarks> ProductMarksActive
        {
            get
            {
                return
                    ProductMarks.Where(p => p.IsActive).Where(q => q.ProductVendors.IsActive);
            }
        }

        /// <summary>
        /// Получить марку продукта по Id
        /// </summary>
        /// <param name="idProductMark">Id марки продукта</param>
        /// <returns>марка продукта</returns>
        public static ProductMarks GetProductMarkbyId(int idProductMark)
        {
            ProductMarks _result = null;
            foreach (ProductMarks productMark in ProductMarks)
            {
                if (productMark.IdProductMark == idProductMark)
                {
                    _result = productMark;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление марки продукта
        /// </summary>
        /// <param name="productMarkItem">марка продукта</param>
        public static void ProductMarksUpdate(ProductMarks productMarkItem)
        {
            if (productMarkItem != null)
            {
                ProductMarks productMarkUpdate = GetProductMarkbyId(productMarkItem.IdProductMark);
                if (productMarkUpdate != null)
                {
                    productMarkUpdate.IsActive = productMarkItem.IsActive;
                    productMarkUpdate.ProductMark = productMarkItem.ProductMark;
                    productMarkUpdate.IdParentProductMark = productMarkItem.IdParentProductMark;
                    productMarkUpdate.IdProductVendor = productMarkItem.IdProductVendor;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление марки продукта
        /// </summary>
        /// <param name="productMarkItem">марка продукта</param>
        public static void ProductMarksInsert(ProductMarks productMarkItem)
        {
            Entities.ProductMarks.AddObject(productMarkItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление марки продукта
        /// </summary>
        /// <param name="productMarkItem">марка продукта</param>
        public static void ProductMarksDelete(ProductMarks productMarkItem)
        {
            if (productMarkItem != null)
            {
                ProductMarks productMarkDel = GetProductMarkbyId(productMarkItem.IdProductMark);
                if (productMarkDel != null)
                {
                    ProductMarks.DeleteObject(productMarkDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Tools

        /// <summary>
        /// Список инструментов
        /// </summary>
        public static ObjectSet<Tools> Tools
        {
            get { return Entities.Tools; }
        }

        /// <summary>
        /// Активные инструменты
        /// </summary>
        public static IQueryable<Tools> ToolsActive
        {
            get
            {
                return
                    Tools.Where(p => p.IsActive).Where(q => q.ToolVendors.IsActive).Where(
                        g => g.ToolGroups.IsActive == true);
            }
        }

        /// <summary>
        /// Получить инструмент по Id
        /// </summary>
        /// <param name="idTool">Id инструмента</param>
        /// <returns>инструмент</returns>
        public static Tools GetToolbyId(int idTool)
        {
            Tools _result = null;
            foreach (Tools tool in Tools)
            {
                if (tool.IdTool == idTool)
                {
                    _result = tool;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление инструмена
        /// </summary>
        /// <param name="toolItem">инструмент</param>
        public static void ToolsUpdate(Tools toolItem)
        {
            if (toolItem != null)
            {
                Tools toolUpdate = GetToolbyId(toolItem.IdTool);
                if (toolUpdate != null)
                {
                    toolUpdate.IsActive = toolItem.IsActive;
                    toolUpdate.Article = toolItem.Article;
                    toolUpdate.Price = toolItem.Price;
                    toolUpdate.IdToolGroup = toolItem.IdToolGroup;
                    toolUpdate.IdVendor = toolItem.IdVendor;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление инструмена
        /// </summary>
        /// <param name="toolItem">инструмент</param>
        public static void ToolsInsert(Tools toolItem)
        {
            Entities.Tools.AddObject(toolItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление инструмена
        /// </summary>
        /// <param name="toolItem">инструмент</param>
        public static void ToolsDelete(Tools toolItem)
        {
            if (toolItem != null)
            {
                Tools toolDel = GetToolbyId(toolItem.IdTool);
                if (toolDel != null)
                {
                    Tools.DeleteObject(toolDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Equipments

        /// <summary>
        /// Список оборудования
        /// </summary>
        public static ObjectSet<Equipments> Equipments
        {
            get { return Entities.Equipments; }
        }


        /// <summary>
        /// Активное оборудование
        /// </summary>
        public static IQueryable<Equipments> EquipmentsActive
        {
            get
            {
                return
                    Equipments.Where(p => p.IsActive).Where(q => q.Vendors.IsActive);
            }
        }

        /// <summary>
        /// Получить оборудование по Id
        /// </summary>
        /// <param name="idEquipment">Id оборудования</param>
        /// <returns>оборудование</returns>
        public static Equipments GetEquipmentbyId(int idEquipment)
        {
            Equipments _result = null;
            foreach (Equipments equipment in Equipments)
            {
                if (equipment.IdEquipment == idEquipment)
                {
                    _result = equipment;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Получить оборудование по названию
        /// </summary>
        /// <param name="equipmentName">Название оборудования</param>
        /// <returns>оборудование</returns>
        public static Equipments GetEquipmentbyName(string equipmentName)
        {
            Equipments _result = null;
            foreach (Equipments equipment in Equipments)
            {
                if (equipment.Model == equipmentName)
                {
                    _result = equipment;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление оборудования
        /// </summary>
        /// <param name="equipmentItem">оборудование</param>
        public static void EquipmentsUpdate(Equipments equipmentItem)
        {
            if (equipmentItem != null)
            {
                Equipments equipmentUpdate = GetEquipmentbyId(equipmentItem.IdEquipment);
                if (equipmentUpdate != null)
                {
                    equipmentUpdate.IsActive = equipmentItem.IsActive;
                    equipmentUpdate.Model = equipmentItem.Model;
                    equipmentUpdate.IdEquipmentType = equipmentItem.IdEquipmentType;
                    equipmentUpdate.IdVendor = equipmentItem.IdVendor;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление оборудования
        /// </summary>
        /// <param name="equipmentItem">оборудование</param>
        public static void EquipmentsInsert(Equipments equipmentItem)
        {
            Entities.Equipments.AddObject(equipmentItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление оборудования
        /// </summary>
        /// <param name="equipmentItem">оборудование</param>
        public static void EquipmentsDelete(Equipments equipmentItem)
        {
            if (equipmentItem != null)
            {
                Equipments equipmentDel = GetEquipmentbyId(equipmentItem.IdEquipment);
                if (equipmentDel != null)
                {
                    Equipments.DeleteObject(equipmentDel);
                    DB.Save();
                }
            }
        }

        #endregion

        //#region ToolVendors

        ///// <summary>
        ///// Список поставщиков
        ///// </summary>
        ////public static ObjectSet<ToolVendors> ToolVendors
        ////{
        ////    get { return Entities.ToolVendors; }
        ////}

        ///// <summary>
        ///// Активные поставщики
        ///// </summary>
        ////public static IQueryable<ToolVendors> ToolVendorsActive
        ////{
        ////    get
        ////    {
        ////        return
        ////            ToolVendors.Where(p => p.IsActive);
        ////    }
        ////}

        ///// <summary>
        ///// Получить поставщика по Id
        ///// </summary>
        ///// <param name="idToolVendor">Id поставщика</param>
        ///// <returns>поставщика</returns>
        ////public static ToolVendors GetToolVendorbyId(int idToolVendor)
        ////{
        ////    ToolVendors _result = null;
        ////    foreach (ToolVendors toolVendor in ToolVendors)
        ////    {
        ////        if (toolVendor.IdToolVendor == idToolVendor)
        ////        {
        ////            _result = toolVendor;
        ////            break;
        ////        }
        ////    }
        ////    return _result;
        ////}

        ///// <summary>
        ///// Обновление поставщика
        ///// </summary>
        ///// <param name="toolVendorItem">поставщик</param>
        ////public static void ToolVendorsUpdate(ToolVendors toolVendorItem)
        ////{
        ////    if (toolVendorItem != null)
        ////    {
        ////        ToolVendors toolVendorkUpdate = GetToolVendorbyId(toolVendorItem.IdToolVendor);
        ////        if (toolVendorkUpdate != null)
        ////        {
        ////            toolVendorkUpdate.IsActive = toolVendorItem.IsActive;
        ////            toolVendorkUpdate.ToolVendor = toolVendorItem.ToolVendor;

        ////            DB.Save();
        ////        }
        ////    }
        ////}

        ///// <summary>
        ///// Добавление поставщика
        ///// </summary>
        ///// <param name="toolVendorItem">поставщик</param>
        //public static void ToolVendorsInsert(ToolVendors toolVendorItem)
        //{
        //    Entities.ToolVendors.AddObject(toolVendorItem);
        //    DB.Save();
        //}

        ///// <summary>
        ///// Удаление поставщика
        ///// </summary>
        ///// <param name="toolVendorItem">поставщик</param>
        //public static void ToolVendorsDelete(ToolVendors toolVendorItem)
        //{
        //    if (toolVendorItem != null)
        //    {
        //        ToolVendors toolVendorDel = GetToolVendorbyId(toolVendorItem.IdToolVendor);
        //        if (toolVendorDel != null)
        //        {
        //            ToolVendors.DeleteObject(toolVendorDel);
        //            DB.Save();
        //        }
        //    }
        //}

        //#endregion

        #region ToolGroups

        /// <summary>
        /// Список групп инструментов
        /// </summary>
        public static ObjectSet<ToolGroups> ToolGroups
        {
            get { return Entities.ToolGroups; }
        }

        /// <summary>
        /// Активные группы инструметнов
        /// </summary>
        public static IQueryable<ToolGroups> ToolGroupsActive
        {
            get
            {
                return
                    ToolGroups.Where(p => p.IsActive == true);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedToolGroupsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (ToolGroups item in ToolGroupsActive)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdToolGroup;
                listItem.ParentCollection = ToolGroups;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.ToolGroupRu;
                }
                else
                {
                    listItem.LocaLizedString = item.ToolGroupEn;
                }
                result.Add(listItem);
            }
            return result;
        }


        /// <summary>
        /// Получить группу инструментов по Id
        /// </summary>
        /// <param name="idToolGroup">Id группы инструментов</param>
        /// <returns>группа инструментов</returns>
        public static ToolGroups GetToolGroupbyId(int idToolGroup)
        {
            ToolGroups _result = null;
            foreach (ToolGroups toolGroup in ToolGroups)
            {
                if (toolGroup.IdToolGroup == idToolGroup)
                {
                    _result = toolGroup;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление группы продуктов
        /// </summary>
        /// <param name="toolGroupItem">группа продуктов</param>
        public static void ToolGroupsUpdate(ToolGroups toolGroupItem)
        {
            if (toolGroupItem != null)
            {
                ToolGroups toolGroupUpdate = GetToolGroupbyId(toolGroupItem.IdToolGroup);
                if (toolGroupUpdate != null)
                {
                    toolGroupUpdate.IsActive = toolGroupItem.IsActive;
                    toolGroupUpdate.ToolGroupEn = toolGroupItem.ToolGroupEn;
                    toolGroupUpdate.ToolGroupRu = toolGroupItem.ToolGroupRu;
                    toolGroupUpdate.IdParentToolGroup = toolGroupItem.IdParentToolGroup;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление группы продуктов
        /// </summary>
        /// <param name="toolGroupItem">группа продуктов</param>
        public static void ToolGroupsInsert(ToolGroups toolGroupItem)
        {
            Entities.ToolGroups.AddObject(toolGroupItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление группы продуктов
        /// </summary>
        /// <param name="toolGroupItem">группа продуктов</param>
        public static void ToolGroupsDelete(ToolGroups toolGroupItem)
        {
            if (toolGroupItem != null)
            {
                ToolGroups toolGroupDel = GetToolGroupbyId(toolGroupItem.IdToolGroup);
                if (toolGroupDel != null)
                {
                    ToolGroups.DeleteObject(toolGroupDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region EquipmentTypes

        /// <summary>
        /// Список типов оборудования
        /// </summary>
        public static ObjectSet<EquipmentTypes> EquipmentTypes
        {
            get { return Entities.EquipmentTypes; }
        }

        /// <summary>
        /// Активные типы оборудования
        /// </summary>
        public static IQueryable<EquipmentTypes> EquipmentTypesActive
        {
            get
            {
                return
                    EquipmentTypes.Where(p => p.IsActive);
            }
        }


        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedEquipmentTypes(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (EquipmentTypes item in EquipmentTypes)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem { Id = item.IdEquipmentType, ParentCollection = TrainingsPlaces };
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.EquipmentTypeRu;
                }
                else
                {
                    listItem.LocaLizedString = item.EquipmentTypeEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить тип оборудования по Id
        /// </summary>
        /// <param name="idEquipmentType">Id типа оборудования</param>
        /// <returns>тип оборудования</returns>
        public static EquipmentTypes GetEquipmentTypebyId(int idEquipmentType)
        {
            EquipmentTypes _result = null;
            foreach (EquipmentTypes equipmentType in EquipmentTypes)
            {
                if (equipmentType.IdEquipmentType == idEquipmentType)
                {
                    _result = equipmentType;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление типа оборудования
        /// </summary>
        /// <param name="equipmentTypeItem">тип оборудования</param>
        public static void EquipmentTypesUpdate(EquipmentTypes equipmentTypeItem)
        {
            if (equipmentTypeItem != null)
            {
                EquipmentTypes equipmentTypeUpdate = GetEquipmentTypebyId(equipmentTypeItem.IdEquipmentType);
                if (equipmentTypeUpdate != null)
                {
                    equipmentTypeUpdate.IsActive = equipmentTypeItem.IsActive;
                    equipmentTypeUpdate.EquipmentTypeRu = equipmentTypeItem.EquipmentTypeRu;
                    equipmentTypeUpdate.EquipmentTypeEn = equipmentTypeItem.EquipmentTypeEn;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление типа оборудовнаия
        /// </summary>
        /// <param name="equipmentTypeItem">тип оборудования</param>
        public static void EquipmentTypesInsert(EquipmentTypes equipmentTypeItem)
        {
            Entities.EquipmentTypes.AddObject(equipmentTypeItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление типа оборудования
        /// </summary>
        /// <param name="equipmentTypeItem">тип оборудования</param>
        public static void EquipmentTypesDelete(EquipmentTypes equipmentTypeItem)
        {
            if (equipmentTypeItem != null)
            {
                EquipmentTypes equipmentTypekDel = GetEquipmentTypebyId(equipmentTypeItem.IdEquipmentType);
                if (equipmentTypekDel != null)
                {
                    EquipmentTypes.DeleteObject(equipmentTypekDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region TrainingCoursesTypes

        /// <summary>
        /// Список типов учебных курсов
        /// </summary>
        public static ObjectSet<TrainingCoursesTypes> TrainingCoursesTypes
        {
            get { return Entities.TrainingCoursesTypes; }
        }

        /// <summary>
        /// Активные инструменты
        /// </summary>
        public static IQueryable<TrainingCoursesTypes> TrainingCoursesTypesActive
        {
            get
            {
                return
                    TrainingCoursesTypes.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedTrainingCoursesTypesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (TrainingCoursesTypes item in TrainingCoursesTypes)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdTrainingCoursesType;
                listItem.ParentCollection = TrainingCoursesTypes;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить список типов учебных курсов
        /// </summary>
        /// <param name="idTrainingCoursesType">Id списка учебного курса</param>
        /// <returns>список типов учебных курсов</returns>
        public static TrainingCoursesTypes GetTrainingCoursesTypebyId(int idTrainingCoursesType)
        {
            TrainingCoursesTypes _result = null;
            foreach (TrainingCoursesTypes trainingCoursesType in TrainingCoursesTypes)
            {
                if (trainingCoursesType.IdTrainingCoursesType == idTrainingCoursesType)
                {
                    _result = trainingCoursesType;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление списка типов учебных курсов
        /// </summary>
        /// <param name="trainingCoursesTypeItem">тип учебного курса</param>
        public static void TrainingCoursesTypesUpdate(TrainingCoursesTypes trainingCoursesTypeItem)
        {
            if (trainingCoursesTypeItem != null)
            {
                TrainingCoursesTypes trainingCoursesTypeUpdate =
                    GetTrainingCoursesTypebyId(trainingCoursesTypeItem.IdTrainingCoursesType);
                if (trainingCoursesTypeUpdate != null)
                {
                    trainingCoursesTypeUpdate.IsActive = trainingCoursesTypeItem.IsActive;
                    trainingCoursesTypeUpdate.NameEn = trainingCoursesTypeItem.NameEn;
                    trainingCoursesTypeUpdate.NameRu = trainingCoursesTypeItem.NameRu;
                    trainingCoursesTypeUpdate.DescriptionEn = trainingCoursesTypeItem.DescriptionEn;
                    trainingCoursesTypeUpdate.DescriptionRu = trainingCoursesTypeItem.DescriptionRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление списка типов учебных курсов
        /// </summary>
        /// <param name="trainingCoursesTypeItem">тип учебных курсов</param>
        public static void TrainingCoursesTypesInsert(TrainingCoursesTypes trainingCoursesTypeItem)
        {
            Entities.TrainingCoursesTypes.AddObject(trainingCoursesTypeItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление списка типов учебных курсов
        /// </summary>
        /// <param name="trainingCoursesTypeItem">группа продуктов</param>
        public static void TrainingCoursesTypesDelete(TrainingCoursesTypes trainingCoursesTypeItem)
        {
            if (trainingCoursesTypeItem != null)
            {
                TrainingCoursesTypes trainingCoursesTypeDel =
                    GetTrainingCoursesTypebyId(trainingCoursesTypeItem.IdTrainingCoursesType);
                if (trainingCoursesTypeDel != null)
                {
                    TrainingCoursesTypes.DeleteObject(trainingCoursesTypeDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Rubrics

        /// <summary>
        /// Список рубрик
        /// </summary>
        public static ObjectSet<Rubrics> Rubrics
        {
            get { return Entities.Rubrics; }
        }

        /// <summary>
        /// Активные рубрики
        /// </summary>
        public static IQueryable<Rubrics> RubricsActive
        {
            get
            {
                return
                    Rubrics.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedRubricsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (Rubrics item in Rubrics)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdRubric;
                listItem.ParentCollection = Rubrics;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }


        /// <summary>
        /// Получить рубрику по Id
        /// </summary>
        /// <param name="idRubric">Id рубрики</param>
        /// <returns>рубрика</returns>
        public static Rubrics GetRubricbyId(int idRubric)
        {
            Rubrics _result = null;
            foreach (Rubrics rubric in Rubrics)
            {
                if (rubric.IdRubric == idRubric)
                {
                    _result = rubric;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление рубрик
        /// </summary>
        /// <param name="rubricItem">рубрика</param>
        public static void RubricsUpdate(Rubrics rubricItem)
        {
            if (rubricItem != null)
            {
                Rubrics rubricUpdate = GetRubricbyId(rubricItem.IdRubric);
                if (rubricUpdate != null)
                {
                    rubricUpdate.IsActive = rubricItem.IsActive;
                    rubricUpdate.NameEn = rubricItem.NameEn;
                    rubricUpdate.NameRu = rubricItem.NameRu;
                    rubricUpdate.DescriptionEn = rubricItem.DescriptionEn;
                    rubricUpdate.DescriptionRu = rubricItem.DescriptionRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление рубрики
        /// </summary>
        /// <param name="rubricsItem">рубрика</param>
        public static void RubricsInsert(Rubrics rubricsItem)
        {
            Entities.Rubrics.AddObject(rubricsItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление рубрики
        /// </summary>
        /// <param name="rubricItem">рубрика</param>
        public static void RubricsDelete(Rubrics rubricItem)
        {
            if (rubricItem != null)
            {
                Rubrics rubricDel = GetRubricbyId(rubricItem.IdRubric);
                if (rubricDel != null)
                {
                    Rubrics.DeleteObject(rubricDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region TrainingCoursesStatuses

        /// <summary>
        /// Список статусов курсов
        /// </summary>
        public static ObjectSet<TrainingCoursesStatuses> TrainingCoursesStatuses
        {
            get { return Entities.TrainingCoursesStatuses; }
        }

        /// <summary>
        /// Активные статусы курсов
        /// </summary>
        public static IQueryable<TrainingCoursesStatuses> TrainingCoursesStatusesActive
        {
            get
            {
                return
                    TrainingCoursesStatuses.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedTrainingCoursesStatusesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (TrainingCoursesStatuses item in TrainingCoursesStatuses)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdTrainingCoursesStatus;
                listItem.ParentCollection = TrainingCoursesStatuses;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить список статусов курсов по Id
        /// </summary>
        /// <param name="idTrainingCoursesStatus">Id статуса курсов</param>
        /// <returns>статус курсов</returns>
        public static TrainingCoursesStatuses GetTrainingCoursesStatusbyId(int idTrainingCoursesStatus)
        {
            TrainingCoursesStatuses _result = null;
            foreach (TrainingCoursesStatuses trainingCoursesStatus in TrainingCoursesStatuses)
            {
                if (trainingCoursesStatus.IdTrainingCoursesStatus == idTrainingCoursesStatus)
                {
                    _result = trainingCoursesStatus;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление списка статусов курсов
        /// </summary>
        /// <param name="trainingCoursesStatusItem">статус курсов</param>
        public static void TrainingCoursesStatusesUpdate(TrainingCoursesStatuses trainingCoursesStatusItem)
        {
            if (trainingCoursesStatusItem != null)
            {
                TrainingCoursesStatuses trainingCoursesStatusUpdate =
                    GetTrainingCoursesStatusbyId(trainingCoursesStatusItem.IdTrainingCoursesStatus);
                if (trainingCoursesStatusUpdate != null)
                {
                    trainingCoursesStatusUpdate.IsActive = trainingCoursesStatusItem.IsActive;
                    trainingCoursesStatusUpdate.NameEn = trainingCoursesStatusItem.NameEn;
                    trainingCoursesStatusUpdate.NameRu = trainingCoursesStatusItem.NameRu;
                    trainingCoursesStatusUpdate.DescriptionEn = trainingCoursesStatusItem.DescriptionEn;
                    trainingCoursesStatusUpdate.DescriptionRu = trainingCoursesStatusItem.DescriptionRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление статусов курсов
        /// </summary>
        /// <param name="trainingCoursesStatusItem">статус курсов</param>
        public static void TrainingCoursesStatusesInsert(TrainingCoursesStatuses trainingCoursesStatusItem)
        {
            Entities.TrainingCoursesStatuses.AddObject(trainingCoursesStatusItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление статусов курсов
        /// </summary>
        /// <param name="trainingCoursesStatusItem">статус курсов</param>
        public static void TrainingCoursesStatusesDelete(TrainingCoursesStatuses trainingCoursesStatusItem)
        {
            if (trainingCoursesStatusItem != null)
            {
                TrainingCoursesStatuses trainingCoursesStatusDel =
                    GetTrainingCoursesStatusbyId(trainingCoursesStatusItem.IdTrainingCoursesStatus);
                if (trainingCoursesStatusDel != null)
                {
                    TrainingCoursesStatuses.DeleteObject(trainingCoursesStatusDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region TrainigAuditoriums

        /// <summary>
        /// Список целевых аудиторий
        /// </summary>
        public static ObjectSet<TrainigAuditoriums> TrainigAuditoriums
        {
            get { return Entities.TrainigAuditoriums; }
        }

        /// <summary>
        /// Активные цлевые аудитории
        /// </summary>
        public static IQueryable<TrainigAuditoriums> TrainigAuditoriumsActive
        {
            get
            {
                return
                    TrainigAuditoriums.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedTrainigAuditoriumsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (TrainigAuditoriums item in TrainigAuditoriums)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdTrainigAuditorium;
                listItem.ParentCollection = TrainigAuditoriums;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить список целевых аудиторий по Id
        /// </summary>
        /// <param name="idTrainigAuditorium">Id целевой аудитории</param>
        /// <returns>целевая аудитория</returns>
        public static TrainigAuditoriums GetTrainigAuditoriumbyId(int idTrainigAuditorium)
        {
            TrainigAuditoriums _result = null;
            foreach (TrainigAuditoriums trainigAuditorium in TrainigAuditoriums)
            {
                if (trainigAuditorium.IdTrainigAuditorium == idTrainigAuditorium)
                {
                    _result = trainigAuditorium;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление целевых аудиторий
        /// </summary>
        /// <param name="trainigAuditoriumItem">целевая аудитория</param>
        public static void TrainigAuditoriumsUpdate(TrainigAuditoriums trainigAuditoriumItem)
        {
            if (trainigAuditoriumItem != null)
            {
                TrainigAuditoriums trainigAuditoriumUpdate =
                    GetTrainigAuditoriumbyId(trainigAuditoriumItem.IdTrainigAuditorium);
                if (trainigAuditoriumUpdate != null)
                {
                    trainigAuditoriumUpdate.IsActive = trainigAuditoriumItem.IsActive;
                    trainigAuditoriumUpdate.NameEn = trainigAuditoriumItem.NameEn;
                    trainigAuditoriumUpdate.NameRu = trainigAuditoriumItem.NameRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление целевых аудиторий
        /// </summary>
        /// <param name="trainigAuditoriumItem">целевая аудитория</param>
        public static void TrainigAuditoriumsInsert(TrainigAuditoriums trainigAuditoriumItem)
        {
            Entities.TrainigAuditoriums.AddObject(trainigAuditoriumItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление целевых аудиторий
        /// </summary>
        /// <param name="trainigAuditoriumItem">целевая аудитория</param>
        public static void TrainigAuditoriumsDelete(TrainigAuditoriums trainigAuditoriumItem)
        {
            if (trainigAuditoriumItem != null)
            {
                TrainigAuditoriums trainigAuditoriumDel =
                    GetTrainigAuditoriumbyId(trainigAuditoriumItem.IdTrainigAuditorium);
                if (trainigAuditoriumDel != null)
                {
                    TrainigAuditoriums.DeleteObject(trainigAuditoriumDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region TrainingRequestsStatuses

        /// <summary>
        /// Список статус заявки на обучение
        /// </summary>
        public static ObjectSet<TrainingRequestsStatuses> TrainingRequestsStatuses
        {
            get { return Entities.TrainingRequestsStatuses; }
        }

        /// <summary>
        /// Активные статусы заявок на обучение
        /// </summary>
        public static IQueryable<TrainingRequestsStatuses> TrainingRequestsStatusesActive
        {
            get
            {
                return
                    TrainingRequestsStatuses.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedTrainingRequestsStatusesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (TrainingRequestsStatuses item in TrainingRequestsStatuses)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdTrainingRequestsStatus;
                listItem.ParentCollection = TrainingRequestsStatuses;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить статус заявки на обучение по Id
        /// </summary>
        /// <param name="idTrainingRequestsStatus">Id статуса заявки на обучение</param>
        /// <returns>заявка на обучение</returns>
        public static TrainingRequestsStatuses GetTrainingRequestsStatusbyId(int idTrainingRequestsStatus)
        {
            TrainingRequestsStatuses _result = null;
            foreach (TrainingRequestsStatuses trainingRequestsStatus in TrainingRequestsStatuses)
            {
                if (trainingRequestsStatus.IdTrainingRequestsStatus == idTrainingRequestsStatus)
                {
                    _result = trainingRequestsStatus;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление статуса заявки на обучение
        /// </summary>
        /// <param name="trainingRequestsStatusItem">статус заявки на обучение</param>
        public static void TrainingRequestsStatusesUpdate(TrainingRequestsStatuses trainingRequestsStatusItem)
        {
            if (trainingRequestsStatusItem != null)
            {
                TrainingRequestsStatuses trainingRequestsStatusUpdate =
                    GetTrainingRequestsStatusbyId(trainingRequestsStatusItem.IdTrainingRequestsStatus);
                if (trainingRequestsStatusUpdate != null)
                {
                    trainingRequestsStatusUpdate.IsActive = trainingRequestsStatusItem.IsActive;
                    trainingRequestsStatusUpdate.NameEn = trainingRequestsStatusItem.NameEn;
                    trainingRequestsStatusUpdate.NameRu = trainingRequestsStatusItem.NameRu;
                    trainingRequestsStatusUpdate.DescriptionEn = trainingRequestsStatusItem.DescriptionEn;
                    trainingRequestsStatusUpdate.DescriptionRu = trainingRequestsStatusItem.DescriptionRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление статуса заявки на обучение
        /// </summary>
        /// <param name="trainingRequestsStatusItem">статус заявки на обучение</param>
        public static void TrainingRequestsStatusesInsert(TrainingRequestsStatuses trainingRequestsStatusItem)
        {
            Entities.TrainingRequestsStatuses.AddObject(trainingRequestsStatusItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление статуса заявки на обучение
        /// </summary>
        /// <param name="trainingRequestsStatusItem">статус заявки на обучение</param>
        public static void TrainingRequestsStatusesDelete(TrainingRequestsStatuses trainingRequestsStatusItem)
        {
            if (trainingRequestsStatusItem != null)
            {
                TrainingRequestsStatuses trainingRequestsStatusDel =
                    GetTrainingRequestsStatusbyId(trainingRequestsStatusItem.IdTrainingRequestsStatus);
                if (trainingRequestsStatusDel != null)
                {
                    TrainingRequestsStatuses.DeleteObject(trainingRequestsStatusDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region TrainingParticipantsStatuses

        /// <summary>
        /// Список статусов участников
        /// </summary>
        public static ObjectSet<TrainingParticipantsStatuses> TrainingParticipantsStatuses
        {
            get { return Entities.TrainingParticipantsStatuses; }
        }

        /// <summary>
        /// Активные статусы участников
        /// </summary>
        public static IQueryable<TrainingParticipantsStatuses> TrainingParticipantsStatusesActive
        {
            get
            {
                return
                    TrainingParticipantsStatuses.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedTrainingParticipantsStatusesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (TrainingParticipantsStatuses item in TrainingParticipantsStatuses)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdTrainingParticipantsStatus;
                listItem.ParentCollection = TrainingParticipantsStatuses;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить статус участника по Id
        /// </summary>
        /// <param name="idTrainingParticipantsStatus">Id статуса участника</param>
        /// <returns>целевая аудитория</returns>
        public static TrainingParticipantsStatuses GetTrainingParticipantsStatusbyId(int idTrainingParticipantsStatus)
        {
            TrainingParticipantsStatuses _result = null;
            foreach (TrainingParticipantsStatuses trainingParticipantsStatus in TrainingParticipantsStatuses)
            {
                if (trainingParticipantsStatus.IdTrainingParticipantsStatus == idTrainingParticipantsStatus)
                {
                    _result = trainingParticipantsStatus;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление статуса участника
        /// </summary>
        /// <param name="trainingParticipantsStatusItem">статус участника</param>
        public static void TrainingParticipantsStatusesUpdate(
            TrainingParticipantsStatuses trainingParticipantsStatusItem)
        {
            if (trainingParticipantsStatusItem != null)
            {
                TrainingParticipantsStatuses trainingParticipantsStatusUpdate =
                    GetTrainingParticipantsStatusbyId(trainingParticipantsStatusItem.IdTrainingParticipantsStatus);
                if (trainingParticipantsStatusUpdate != null)
                {
                    trainingParticipantsStatusUpdate.IsActive = trainingParticipantsStatusItem.IsActive;
                    trainingParticipantsStatusUpdate.NameEn = trainingParticipantsStatusItem.NameEn;
                    trainingParticipantsStatusUpdate.NameRu = trainingParticipantsStatusItem.NameRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление статуса участника
        /// </summary>
        /// <param name="trainingParticipantsStatusItem">статус участника</param>
        public static void TrainingParticipantsStatusesInsert(
            TrainingParticipantsStatuses trainingParticipantsStatusItem)
        {
            Entities.TrainingParticipantsStatuses.AddObject(trainingParticipantsStatusItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление статуса участника
        /// </summary>
        /// <param name="trainingParticipantsStatusItem">статус участника</param>
        public static void TrainingParticipantsStatusesDelete(
            TrainingParticipantsStatuses trainingParticipantsStatusItem)
        {
            if (trainingParticipantsStatusItem != null)
            {
                TrainingParticipantsStatuses trainingParticipantsStatusDel =
                    GetTrainingParticipantsStatusbyId(trainingParticipantsStatusItem.IdTrainingParticipantsStatus);
                if (trainingParticipantsStatusDel != null)
                {
                    TrainingParticipantsStatuses.DeleteObject(trainingParticipantsStatusDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region CustomerClassificationsProfine

        /// <summary>
        /// Список классификаций по роду деятельности
        /// </summary>
        public static ObjectSet<CustomerClassificationsProfine> CustomerClassificationsProfine
        {
            get { return Entities.CustomerClassificationsProfine; }
        }

        /// <summary>
        /// Активные классификации по роду деятельности
        /// </summary>
        public static IQueryable<CustomerClassificationsProfine> CustomerClassificationsProfineActive
        {
            get
            {
                return
                    CustomerClassificationsProfine.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedCustomerClassificationsProfineNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (CustomerClassificationsProfine item in CustomerClassificationsProfine)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdCustomerClassificationsProfine;
                listItem.ParentCollection = CustomerClassificationsProfine;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить классификацию по роду деятельности по Id
        /// </summary>
        /// <param name="idCustomerClassificationsProfine">Id классификации по роду деятельности</param>
        /// <returns>классификация по роду деятельности</returns>
        public static CustomerClassificationsProfine GetCustomerClassificationsProfinebyId(
            int idCustomerClassificationsProfine)
        {
            CustomerClassificationsProfine _result = null;
            foreach (CustomerClassificationsProfine trainigAuditorium in CustomerClassificationsProfine)
            {
                if (trainigAuditorium.IdCustomerClassificationsProfine == idCustomerClassificationsProfine)
                {
                    _result = trainigAuditorium;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление классификации по роду деятельности
        /// </summary>
        /// <param name="customerClassificationsProfineItem">классификация по роду деятельности</param>
        public static void CustomerClassificationsProfineUpdate(
            CustomerClassificationsProfine customerClassificationsProfineItem)
        {
            if (customerClassificationsProfineItem != null)
            {
                CustomerClassificationsProfine customerClassificationsProfineUpdate =
                    GetCustomerClassificationsProfinebyId(
                        customerClassificationsProfineItem.IdCustomerClassificationsProfine);
                if (customerClassificationsProfineUpdate != null)
                {
                    customerClassificationsProfineUpdate.IsActive = customerClassificationsProfineItem.IsActive;
                    customerClassificationsProfineUpdate.NameEn = customerClassificationsProfineItem.NameEn;
                    customerClassificationsProfineUpdate.NameRu = customerClassificationsProfineItem.NameRu;
                    customerClassificationsProfineUpdate.DescriptionEn =
                        customerClassificationsProfineItem.DescriptionEn;
                    customerClassificationsProfineUpdate.DescriptionRu =
                        customerClassificationsProfineItem.DescriptionRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление классификации по роду деятельности
        /// </summary>
        /// <param name="customerClassificationsProfineItem">классификация по роду деятельности</param>
        public static void CustomerClassificationsProfineInsert(
            CustomerClassificationsProfine customerClassificationsProfineItem)
        {
            Entities.CustomerClassificationsProfine.AddObject(customerClassificationsProfineItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление классификации по роду деятельности
        /// </summary>
        /// <param name="customerClassificationsProfineItem">классификация по роду деятельности</param>
        public static void CustomerClassificationsProfineDelete(
            CustomerClassificationsProfine customerClassificationsProfineItem)
        {
            if (customerClassificationsProfineItem != null)
            {
                CustomerClassificationsProfine customerClassificationsProfineDel =
                    GetCustomerClassificationsProfinebyId(
                        customerClassificationsProfineItem.IdCustomerClassificationsProfine);
                if (customerClassificationsProfineDel != null)
                {
                    CustomerClassificationsProfine.DeleteObject(customerClassificationsProfineDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region CustomerClassificationsTurnover

        /// <summary>
        /// Список классификаций по оборотам
        /// </summary>
        public static ObjectSet<CustomerClassificationsTurnover> CustomerClassificationsTurnover
        {
            get { return Entities.CustomerClassificationsTurnover; }
        }

        /// <summary>
        /// Активные классификации по оборотам
        /// </summary>
        public static IQueryable<CustomerClassificationsTurnover> CustomerClassificationsTurnoverActive
        {
            get
            {
                return
                    CustomerClassificationsTurnover.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedCustomerClassificationsTurnoverNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (CustomerClassificationsTurnover item in CustomerClassificationsTurnover)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdCustomerClassificationsTurnover;
                listItem.ParentCollection = CustomerClassificationsTurnover;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить классификацию по оборотам по Id
        /// </summary>
        /// <param name="idCustomerClassificationsTurnover">Id классификации по оборотам</param>
        /// <returns>целевая аудитория</returns>
        public static CustomerClassificationsTurnover GetCustomerClassificationsTurnoverbyId(
            int idCustomerClassificationsTurnover)
        {
            CustomerClassificationsTurnover _result = null;
            foreach (CustomerClassificationsTurnover customerClassificationsTurnover in CustomerClassificationsTurnover)
            {
                if (customerClassificationsTurnover.IdCustomerClassificationsTurnover ==
                    idCustomerClassificationsTurnover)
                {
                    _result = customerClassificationsTurnover;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление классификации по оборотам
        /// </summary>
        /// <param name="customerClassificationsTurnoverItem">классификация по оборотам</param>
        public static void CustomerClassificationsTurnoverUpdate(
            CustomerClassificationsTurnover customerClassificationsTurnoverItem)
        {
            if (customerClassificationsTurnoverItem != null)
            {
                CustomerClassificationsTurnover customerClassificationsTurnoverUpdate =
                    GetCustomerClassificationsTurnoverbyId(
                        customerClassificationsTurnoverItem.IdCustomerClassificationsTurnover);
                if (customerClassificationsTurnoverUpdate != null)
                {
                    customerClassificationsTurnoverUpdate.IsActive = customerClassificationsTurnoverItem.IsActive;
                    customerClassificationsTurnoverUpdate.NameEn = customerClassificationsTurnoverItem.NameEn;
                    customerClassificationsTurnoverUpdate.NameRu = customerClassificationsTurnoverItem.NameRu;
                    customerClassificationsTurnoverUpdate.DescriptionEn = customerClassificationsTurnoverItem.DescriptionEn;
                    customerClassificationsTurnoverUpdate.DescriptionRu = customerClassificationsTurnoverItem.DescriptionRu;


                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление классификации по оборотам
        /// </summary>
        /// <param name="customerClassificationsTurnoverItem">классификация по оборотам</param>
        public static void CustomerClassificationsTurnoverInsert(
            CustomerClassificationsTurnover customerClassificationsTurnoverItem)
        {
            Entities.CustomerClassificationsTurnover.AddObject(customerClassificationsTurnoverItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление классификации по оборотам
        /// </summary>
        /// <param name="customerClassificationsTurnoverItem">классификация по оборотам</param>
        public static void CustomerClassificationsTurnoverDelete(
            CustomerClassificationsTurnover customerClassificationsTurnoverItem)
        {
            if (customerClassificationsTurnoverItem != null)
            {
                CustomerClassificationsTurnover customerClassificationsTurnoverDel =
                    GetCustomerClassificationsTurnoverbyId(
                        customerClassificationsTurnoverItem.IdCustomerClassificationsTurnover);
                if (customerClassificationsTurnoverDel != null)
                {
                    CustomerClassificationsTurnover.DeleteObject(customerClassificationsTurnoverDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region CustomerClassificationsByBusiness

        /// <summary>
        /// Список классификаций по роду деятельности
        /// </summary>
        public static ObjectSet<CustomerClassificationsByBusiness> CustomerClassificationsByBusiness
        {
            get { return Entities.CustomerClassificationsByBusiness; }
        }

        /// <summary>
        /// Активные классификации по роду деятельности
        /// </summary>
        public static IQueryable<CustomerClassificationsByBusiness> CustomerClassificationsByBusinessActive
        {
            get
            {
                return
                    CustomerClassificationsByBusiness.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedCustomerClassificationsByBusinessNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (CustomerClassificationsByBusiness item in CustomerClassificationsByBusiness)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdCustomerClassificationsByBusiness;
                listItem.ParentCollection = CustomerClassificationsByBusiness;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить классификацию по роду деятельности по Id
        /// </summary>
        /// <param name="idCustomerClassificationsByBusiness">Id классификации по роду деятельности</param>
        /// <returns>заявка на обучение</returns>
        public static CustomerClassificationsByBusiness GetCustomerClassificationsByBusinessbyId(
            int idCustomerClassificationsByBusiness)
        {
            CustomerClassificationsByBusiness _result = null;
            foreach (
                CustomerClassificationsByBusiness customerClassificationsByBusiness in CustomerClassificationsByBusiness
                )
            {
                if (customerClassificationsByBusiness.IdCustomerClassificationsByBusiness ==
                    idCustomerClassificationsByBusiness)
                {
                    _result = customerClassificationsByBusiness;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление классификации по роду деятельности
        /// </summary>
        /// <param name="customerClassificationsByBusinessItem">классификация по роду деятельности</param>
        public static void CustomerClassificationsByBusinessUpdate(
            CustomerClassificationsByBusiness customerClassificationsByBusinessItem)
        {
            if (customerClassificationsByBusinessItem != null)
            {
                CustomerClassificationsByBusiness customerClassificationsByBusinessUpdate =
                    GetCustomerClassificationsByBusinessbyId(
                        customerClassificationsByBusinessItem.IdCustomerClassificationsByBusiness);
                if (customerClassificationsByBusinessUpdate != null)
                {
                    customerClassificationsByBusinessUpdate.IsActive = customerClassificationsByBusinessItem.IsActive;
                    customerClassificationsByBusinessUpdate.NameEn = customerClassificationsByBusinessItem.NameEn;
                    customerClassificationsByBusinessUpdate.NameRu = customerClassificationsByBusinessItem.NameRu;
                    customerClassificationsByBusinessUpdate.DescriptionEn =
                        customerClassificationsByBusinessItem.DescriptionEn;
                    customerClassificationsByBusinessUpdate.DescriptionRu =
                        customerClassificationsByBusinessItem.DescriptionRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление классификации по роду деятельности
        /// </summary>
        /// <param name="customerClassificationsByBusinessItem">классификация по роду деятельности</param>
        public static void CustomerClassificationsByBusinessInsert(
            CustomerClassificationsByBusiness customerClassificationsByBusinessItem)
        {
            Entities.CustomerClassificationsByBusiness.AddObject(customerClassificationsByBusinessItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление классификации по роду деятельности
        /// </summary>
        /// <param name="customerClassificationsByBusinessItem">классификация по роду деятельности</param>
        public static void CustomerClassificationsByBusinessDelete(
            CustomerClassificationsByBusiness customerClassificationsByBusinessItem)
        {
            if (customerClassificationsByBusinessItem != null)
            {
                CustomerClassificationsByBusiness customerClassificationsByBusinessDel =
                    GetCustomerClassificationsByBusinessbyId(
                        customerClassificationsByBusinessItem.IdCustomerClassificationsByBusiness);
                if (customerClassificationsByBusinessDel != null)
                {
                    CustomerClassificationsByBusiness.DeleteObject(customerClassificationsByBusinessDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region ActivitiesDirections

        /// <summary>
        /// Список направлений
        /// </summary>
        public static ObjectSet<ActivitiesDirections> ActivitiesDirections
        {
            get { return Entities.ActivitiesDirections; }
        }

        /// <summary>
        /// Активные направления
        /// </summary>
        public static IQueryable<ActivitiesDirections> ActivitiesDirectionsActive
        {
            get
            {
                return
                    ActivitiesDirections.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedActivitiesDirectionsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (ActivitiesDirections item in ActivitiesDirections)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdActivitiesDirection;
                listItem.ParentCollection = ActivitiesDirections;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить направление по Id
        /// </summary>
        /// <param name="idActivitiesDirection">Id направления</param>
        /// <returns>заявка на обучение</returns>
        public static ActivitiesDirections GetActivitiesDirectionbyId(int idActivitiesDirection)
        {
            ActivitiesDirections _result = null;
            foreach (ActivitiesDirections activitiesDirection in ActivitiesDirections)
            {
                if (activitiesDirection.IdActivitiesDirection == idActivitiesDirection)
                {
                    _result = activitiesDirection;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление направления
        /// </summary>
        /// <param name="activitiesDirectionItem">направление</param>
        public static void ActivitiesDirectionsUpdate(ActivitiesDirections activitiesDirectionItem)
        {
            if (activitiesDirectionItem != null)
            {
                ActivitiesDirections activitiesDirectionUpdate =
                    GetActivitiesDirectionbyId(activitiesDirectionItem.IdActivitiesDirection);
                if (activitiesDirectionUpdate != null)
                {
                    activitiesDirectionUpdate.IsActive = activitiesDirectionItem.IsActive;
                    activitiesDirectionUpdate.NameEn = activitiesDirectionItem.NameEn;
                    activitiesDirectionUpdate.NameRu = activitiesDirectionItem.NameRu;
                    activitiesDirectionUpdate.DescriptionEn = activitiesDirectionItem.DescriptionEn;
                    activitiesDirectionUpdate.DescriptionRu = activitiesDirectionItem.DescriptionRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление направления
        /// </summary>
        /// <param name="activitiesDirectionItem">направление</param>
        public static void ActivitiesDirectionsInsert(ActivitiesDirections activitiesDirectionItem)
        {
            Entities.ActivitiesDirections.AddObject(activitiesDirectionItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление направления
        /// </summary>
        /// <param name="activitiesDirectionItem">направление</param>
        public static void ActivitiesDirectionsDelete(ActivitiesDirections activitiesDirectionItem)
        {
            if (activitiesDirectionItem != null)
            {
                ActivitiesDirections activitiesDirectionDel =
                    GetActivitiesDirectionbyId(activitiesDirectionItem.IdActivitiesDirection);
                if (activitiesDirectionDel != null)
                {
                    ActivitiesDirections.DeleteObject(activitiesDirectionDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region ActivitiesCategories

        /// <summary>
        /// Список категорий
        /// </summary>
        public static ObjectSet<ActivitiesCategories> ActivitiesCategories
        {
            get { return Entities.ActivitiesCategories; }
        }

        /// <summary>
        /// Активные категории
        /// </summary>
        public static IQueryable<ActivitiesCategories> ActivitiesCategoriesActive
        {
            get
            {
                return
                    ActivitiesCategories.Where(p => p.IsActive == true);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedActivitiesCategoriesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (ActivitiesCategories item in ActivitiesCategories)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdActivitiesCategory;
                listItem.ParentCollection = ActivitiesCategories;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить категорию по Id
        /// </summary>
        /// <param name="idActivitiesCategory">Id статуса заявки на обучение</param>
        /// <returns>заявка на обучение</returns>
        public static ActivitiesCategories GetActivitiesCategorybyId(int idActivitiesCategory)
        {
            ActivitiesCategories _result = null;
            foreach (ActivitiesCategories activitiesCategory in ActivitiesCategories)
            {
                if (activitiesCategory.IdActivitiesCategory == idActivitiesCategory)
                {
                    _result = activitiesCategory;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление категории
        /// </summary>
        /// <param name="activitiesCategoryItem">категория</param>
        public static void ActivitiesCategoriesUpdate(ActivitiesCategories activitiesCategoryItem)
        {
            if (activitiesCategoryItem != null)
            {
                ActivitiesCategories activitiesCategoryUpdate =
                    GetActivitiesCategorybyId(activitiesCategoryItem.IdActivitiesCategory);
                if (activitiesCategoryUpdate != null)
                {
                    activitiesCategoryUpdate.IsActive = activitiesCategoryItem.IsActive;
                    activitiesCategoryUpdate.NameEn = activitiesCategoryItem.NameEn;
                    activitiesCategoryUpdate.NameRu = activitiesCategoryItem.NameRu;
                    activitiesCategoryUpdate.DescriptionEn = activitiesCategoryItem.DescriptionEn;
                    activitiesCategoryUpdate.DescriptionRu = activitiesCategoryItem.DescriptionRu;
                    activitiesCategoryUpdate.IdActivitiesDirection = activitiesCategoryItem.IdActivitiesDirection;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление категории
        /// </summary>
        /// <param name="activitiesCategoryItem">категория</param>
        public static void ActivitiesCategoriesInsert(ActivitiesCategories activitiesCategoryItem)
        {
            Entities.ActivitiesCategories.AddObject(activitiesCategoryItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление категории
        /// </summary>
        /// <param name="activitiesCategoryItem">категория</param>
        public static void ActivitiesCategoriesDelete(ActivitiesCategories activitiesCategoryItem)
        {
            if (activitiesCategoryItem != null)
            {
                ActivitiesCategories activitiesCategoryDel =
                    GetActivitiesCategorybyId(activitiesCategoryItem.IdActivitiesCategory);
                if (activitiesCategoryDel != null)
                {
                    ActivitiesCategories.DeleteObject(activitiesCategoryDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region TrainingsCenters

        /// <summary>
        /// Список центров обучения
        /// </summary>
        public static ObjectSet<TrainingsCenters> TrainingsCenters
        {
            get { return Entities.TrainingsCenters; }
        }

        /// <summary>
        /// Активные центры обучения
        /// </summary>
        public static IQueryable<TrainingsCenters> TrainingsCentersActive
        {
            get
            {
                return
                    TrainingsCenters.Where(p => p.IsActive).Where(q => q.TrainingsCentersTypes.IsActive == true);
            }
        }

        /// <summary>
        /// Получить центр обучени по Id
        /// </summary>
        /// <param name="idTrainingsCenter">Id центра обучения</param>
        /// <returns>заявка на обучение</returns>
        public static TrainingsCenters GetTrainingsCenterbyId(int idTrainingsCenter)
        {
            TrainingsCenters _result = null;
            foreach (TrainingsCenters trainingsCenter in TrainingsCenters)
            {
                if (trainingsCenter.IdTrainingsCenter == idTrainingsCenter)
                {
                    _result = trainingsCenter;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление центра обучения
        /// </summary>
        /// <param name="trainingsCenterItem">центр обучения</param>
        public static void TrainingsCentersUpdate(TrainingsCenters trainingsCenterItem)
        {
            if (trainingsCenterItem != null)
            {
                TrainingsCenters trainingsCenterUpdate = GetTrainingsCenterbyId(trainingsCenterItem.IdTrainingsCenter);
                if (trainingsCenterUpdate != null)
                {
                    trainingsCenterUpdate.IsActive = trainingsCenterItem.IsActive;
                    trainingsCenterUpdate.NameRu = trainingsCenterItem.NameRu;
                    trainingsCenterUpdate.IdTrainingsCentersType = trainingsCenterItem.IdTrainingsCentersType;
                    trainingsCenterUpdate.Phone = trainingsCenterItem.Phone;
                    trainingsCenterUpdate.Email = trainingsCenterItem.Email;
                    trainingsCenterUpdate.CommentsEn = trainingsCenterItem.CommentsEn;
                    trainingsCenterUpdate.CommentsRu = trainingsCenterItem.CommentsRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление центра обучения
        /// </summary>
        /// <param name="trainingsCenterItem">центр обучения</param>
        public static void TrainingsCentersInsert(TrainingsCenters trainingsCenterItem)
        {
            Entities.TrainingsCenters.AddObject(trainingsCenterItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление центра обучения
        /// </summary>
        /// <param name="trainingsCenterItem">центр обучения</param>
        public static void TrainingsCentersDelete(TrainingsCenters trainingsCenterItem)
        {
            if (trainingsCenterItem != null)
            {
                TrainingsCenters trainingsCenterDel = GetTrainingsCenterbyId(trainingsCenterItem.IdTrainingsCenter);
                if (trainingsCenterDel != null)
                {
                    TrainingsCenters.DeleteObject(trainingsCenterDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region TrainingsPlaces

        /// <summary>
        /// Список площадок
        /// </summary>
        public static ObjectSet<TrainingsPlaces> TrainingsPlaces
        {
            get { return Entities.TrainingsPlaces; }
        }

        /// <summary>
        /// Активные площадки
        /// </summary>
        public static IQueryable<TrainingsPlaces> TrainingsPlacesActive
        {
            get
            {
                return
                    TrainingsPlaces.Where(p => p.IsActive).Where(q => q.TrainingsCenters.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedTrainingsPlacesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (TrainingsPlaces item in TrainingsPlaces)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdTrainingsPlace;
                listItem.ParentCollection = TrainingsPlaces;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.NameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.NameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить площадку по Id
        /// </summary>
        /// <param name="idTrainingsPlace">Id площадки</param>
        /// <returns>площадка</returns>
        public static TrainingsPlaces GetTrainingsPlacebyId(int idTrainingsPlace)
        {
            TrainingsPlaces _result = null;
            foreach (TrainingsPlaces trainingsPlace in TrainingsPlaces)
            {
                if (trainingsPlace.IdTrainingsPlace == idTrainingsPlace)
                {
                    _result = trainingsPlace;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление площадки
        /// </summary>
        /// <param name="trainingsPlaceItem">площадка</param>
        public static void TrainingsPlacesUpdate(TrainingsPlaces trainingsPlaceItem)
        {
            if (trainingsPlaceItem != null)
            {
                TrainingsPlaces trainingsPlaceUpdate = GetTrainingsPlacebyId(trainingsPlaceItem.IdTrainingsPlace);
                if (trainingsPlaceUpdate != null)
                {
                    trainingsPlaceUpdate.IsActive = trainingsPlaceItem.IsActive;
                    trainingsPlaceUpdate.NameEn = trainingsPlaceItem.NameEn;
                    trainingsPlaceUpdate.NameRu = trainingsPlaceItem.NameRu;
                    trainingsPlaceUpdate.CommentsEn = trainingsPlaceItem.CommentsEn;
                    trainingsPlaceUpdate.CommentsRu = trainingsPlaceItem.CommentsRu;
                    trainingsPlaceUpdate.IdTrainingsCenter = trainingsPlaceItem.IdTrainingsCenter;
                    trainingsPlaceUpdate.Capacity = trainingsPlaceItem.Capacity;
                    //    trainingsPlaceUpdate.IdUser = IdUser;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление площадки
        /// </summary>
        /// <param name="trainingsPlaceItem">площадка</param>
        public static void TrainingsPlacesInsert(TrainingsPlaces trainingsPlaceItem)
        {
            Entities.TrainingsPlaces.AddObject(trainingsPlaceItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление площадки
        /// </summary>
        /// <param name="trainingsPlaceItem">площадка</param>
        public static void TrainingsPlacesDelete(TrainingsPlaces trainingsPlaceItem)
        {
            if (trainingsPlaceItem != null)
            {
                TrainingsPlaces trainingsPlaceDel = GetTrainingsPlacebyId(trainingsPlaceItem.IdTrainingsPlace);
                if (trainingsPlaceDel != null)
                {
                    TrainingsPlaces.DeleteObject(trainingsPlaceDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region TrainingsTrainers

        /// <summary>
        /// Список тренеров
        /// </summary>
        public static ObjectSet<TrainingsTrainers> TrainingsTrainers
        {
            get { return Entities.TrainingsTrainers; }
        }

        /// <summary>
        /// Активные тренеры
        /// </summary>
        public static IQueryable<TrainingsTrainers> TrainingsTrainersActive
        {
            get
            {
                return
                    TrainingsTrainers.Where(p => p.IsActive).Where(q => q.TrainingsCenters.IsActive);
            }
        }

        /// <summary>
        /// Получить тренера по Id
        /// </summary>
        /// <param name="idTrainingsTrainer">Id тренера</param>
        /// <returns>площадка</returns>
        public static TrainingsTrainers GetTrainingsTrainerbyId(int idTrainingsTrainer)
        {
            TrainingsTrainers _result = null;
            foreach (TrainingsTrainers trainingsTrainer in TrainingsTrainers)
            {
                if (trainingsTrainer.IdTrainingsTrainer == idTrainingsTrainer)
                {
                    _result = trainingsTrainer;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление тренера
        /// </summary>
        /// <param name="trainingsTrainerItem">тренер</param>
        public static void TrainingsTrainersUpdate(TrainingsTrainers trainingsTrainerItem)
        {
            if (trainingsTrainerItem != null)
            {
                TrainingsTrainers trainingsTrainerUpdate =
                    GetTrainingsTrainerbyId(trainingsTrainerItem.IdTrainingsTrainer);
                if (trainingsTrainerUpdate != null)
                {
                    trainingsTrainerUpdate.IsActive = trainingsTrainerItem.IsActive;
                    trainingsTrainerUpdate.IdTrainingsCenter = trainingsTrainerItem.IdTrainingsCenter;
                    trainingsTrainerUpdate.Name = trainingsTrainerItem.Name;
                    trainingsTrainerUpdate.Phone = trainingsTrainerItem.Phone;
                    trainingsTrainerUpdate.Email = trainingsTrainerItem.Email;
                    trainingsTrainerUpdate.CommentsEn = trainingsTrainerItem.CommentsEn;
                    trainingsTrainerUpdate.CommentsRu = trainingsTrainerItem.CommentsRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление тренера
        /// </summary>
        /// <param name="trainingsTrainerItem">тренер</param>
        public static void TrainingsTrainersInsert(TrainingsTrainers trainingsTrainerItem)
        {
            Entities.TrainingsTrainers.AddObject(trainingsTrainerItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление тренера
        /// </summary>
        /// <param name="trainingsTrainerItem">тренер</param>
        public static void TrainingsTrainersDelete(TrainingsTrainers trainingsTrainerItem)
        {
            if (trainingsTrainerItem != null)
            {
                TrainingsTrainers trainingsTrainerDel = GetTrainingsTrainerbyId(trainingsTrainerItem.IdTrainingsTrainer);
                if (trainingsTrainerDel != null)
                {
                    TrainingsTrainers.DeleteObject(trainingsTrainerDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region TrainingsCentersTypes

        /// <summary>
        /// Список типов учебных центров
        /// </summary>
        public static ObjectSet<TrainingsCentersTypes> TrainingsCentersTypes
        {
            get { return Entities.TrainingsCentersTypes; }
        }

        /// <summary>
        /// Активные учебные центры
        /// </summary>
        public static IQueryable<TrainingsCentersTypes> TrainingsCentersTypesActive
        {
            get
            {
                return
                    TrainingsCentersTypes.Where(p => p.IsActive == true);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedTrainingsCentersTypesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (TrainingsCentersTypes item in TrainingsCentersTypes)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdTrainingsCentersType;
                listItem.ParentCollection = TrainingsCentersTypes;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.TypeNameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.TypeNameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить тип учебного центра по Id
        /// </summary>
        /// <param name="idTrainingsCentersType">Id типа учебного центра</param>
        /// <returns>площадка</returns>
        public static TrainingsCentersTypes GetTrainingsCentersTypebyId(int idTrainingsCentersType)
        {
            TrainingsCentersTypes _result = null;
            foreach (TrainingsCentersTypes trainingsCentersType in TrainingsCentersTypes)
            {
                if (trainingsCentersType.IdTrainingsCentersType == idTrainingsCentersType)
                {
                    _result = trainingsCentersType;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление типа учебного цетнра
        /// </summary>
        /// <param name="trainingsCentersTypeItem">тип уебного центра</param>
        public static void TrainingsCentersTypesUpdate(TrainingsCentersTypes trainingsCentersTypeItem)
        {
            if (trainingsCentersTypeItem != null)
            {
                TrainingsCentersTypes trainingsCentersTypeUpdate =
                    GetTrainingsCentersTypebyId(trainingsCentersTypeItem.IdTrainingsCentersType);
                if (trainingsCentersTypeUpdate != null)
                {
                    trainingsCentersTypeUpdate.IsActive = trainingsCentersTypeItem.IsActive;
                    trainingsCentersTypeUpdate.TypeNameRu = trainingsCentersTypeItem.TypeNameRu;
                    trainingsCentersTypeUpdate.TypeNameEn = trainingsCentersTypeItem.TypeNameEn;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление типа учебного цетнра
        /// </summary>
        /// <param name="trainingsCentersTypeItem">тип уебного центра</param>
        public static void TrainingsCentersTypesInsert(TrainingsCentersTypes trainingsCentersTypeItem)
        {
            Entities.TrainingsCentersTypes.AddObject(trainingsCentersTypeItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление типа учебного цетнра
        /// </summary>
        /// <param name="trainingsCentersTypeItem">тип уебного центра</param>
        public static void TrainingsCentersTypesDelete(TrainingsCentersTypes trainingsCentersTypeItem)
        {
            if (trainingsCentersTypeItem != null)
            {
                TrainingsCentersTypes trainingsCentersTypeDel =
                    GetTrainingsCentersTypebyId(trainingsCentersTypeItem.IdTrainingsCentersType);
                if (trainingsCentersTypeDel != null)
                {
                    TrainingsCentersTypes.DeleteObject(trainingsCentersTypeDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region CustomerCategories

        /// <summary>
        /// Список категорий клиентов
        /// </summary>
        public static ObjectSet<CustomerCategories> CustomerCategories
        {
            get { return Entities.CustomerCategories; }
        }

        /// <summary>
        /// Активные категории клиентов
        /// </summary>
        public static IQueryable<CustomerCategories> CustomerCategoriesActive
        {
            get
            {
                return
                    CustomerCategories.Where(p => p.IsActive == true);
            }
        }

        /// <summary>
        /// Получить категорию клиента по Id
        /// </summary>
        /// <param name="idCustomerCategory">Id категории клиента</param>
        /// <returns>категория клиента</returns>
        public static CustomerCategories GetCustomerCategorybyId(int idCustomerCategory)
        {
            CustomerCategories _result = null;
            foreach (CustomerCategories customerCategory in CustomerCategories)
            {
                if (customerCategory.IdCustomerCategory == idCustomerCategory)
                {
                    _result = customerCategory;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление категории клиента
        /// </summary>
        /// <param name="customerCategoryItem">категория клиента</param>
        public static void CustomerCategoriesUpdate(CustomerCategories customerCategoryItem)
        {
            if (customerCategoryItem != null)
            {
                CustomerCategories customerCategoryUpdate =
                    GetCustomerCategorybyId(customerCategoryItem.IdCustomerCategory);
                if (customerCategoryUpdate != null)
                {
                    customerCategoryUpdate.IsActive = customerCategoryItem.IsActive;
                    customerCategoryUpdate.Category = customerCategoryItem.Category;
                    customerCategoryUpdate.DescriptionEn = customerCategoryItem.DescriptionEn;
                    customerCategoryUpdate.DescriptionRu = customerCategoryItem.DescriptionRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление категории клиента
        /// </summary>
        /// <param name="customerCategoryItem">категория клиента</param>
        public static void CustomerCategoriesInsert(CustomerCategories customerCategoryItem)
        {
            Entities.CustomerCategories.AddObject(customerCategoryItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление категории клиента
        /// </summary>
        /// <param name="customerCategoryItem">категория клиента</param>
        public static void CustomerCategoriesDelete(CustomerCategories customerCategoryItem)
        {
            if (customerCategoryItem != null)
            {
                CustomerCategories customerCategoryDel = GetCustomerCategorybyId(customerCategoryItem.IdCustomerCategory);
                if (customerCategoryDel != null)
                {
                    CustomerCategories.DeleteObject(customerCategoryDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region VisitsTypes

        /// <summary>
        /// Список типов выездов
        /// </summary>
        public static ObjectSet<VisitsTypes> VisitsTypes
        {
            get { return Entities.VisitsTypes; }
        }

        /// <summary>
        /// Активные типы выездов
        /// </summary>
        public static IQueryable<VisitsTypes> VisitsTypesActive
        {
            get
            {
                return
                    VisitsTypes.Where(p => p.IsActive == true);
            }
        }

        /// <summary>
        /// Получить тип выезда по Id
        /// </summary>
        /// <param name="idVisitsType">Id типа выезда</param>
        /// <returns>тип выезда</returns>
        public static VisitsTypes GetVisitsTypebyId(int idVisitsType)
        {
            VisitsTypes _result = null;
            foreach (VisitsTypes visitsType in VisitsTypes)
            {
                if (visitsType.IdVisitsType == idVisitsType)
                {
                    _result = visitsType;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление типа выезда
        /// </summary>
        /// <param name="visitsTypeItem">тип выезда</param>
        public static void VisitsTypesUpdate(VisitsTypes visitsTypeItem)
        {
            if (visitsTypeItem != null)
            {
                VisitsTypes visitsTypeUpdate = GetVisitsTypebyId(visitsTypeItem.IdVisitsType);
                if (visitsTypeUpdate != null)
                {
                    visitsTypeUpdate.IsActive = visitsTypeItem.IsActive;
                    visitsTypeUpdate.VisitsType = visitsTypeItem.VisitsType;
                    visitsTypeUpdate.DescriptionEn = visitsTypeItem.DescriptionEn;
                    visitsTypeUpdate.DescriptionRu = visitsTypeItem.DescriptionRu;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление типа выезда
        /// </summary>
        /// <param name="visitsTypeItem">тип выезда</param>
        public static void VisitsTypesInsert(VisitsTypes visitsTypeItem)
        {
            Entities.VisitsTypes.AddObject(visitsTypeItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление типа выезда
        /// </summary>
        /// <param name="visitsTypeItem">тип выезда</param>
        public static void VisitsTypesDelete(VisitsTypes visitsTypeItem)
        {
            if (visitsTypeItem != null)
            {
                VisitsTypes visitsTypeDel = GetVisitsTypebyId(visitsTypeItem.IdVisitsType);
                if (visitsTypeDel != null)
                {
                    VisitsTypes.DeleteObject(visitsTypeDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Roles

        /// <summary>
        /// Список ролей
        /// </summary>
        public static ObjectSet<Roles> Roles
        {
            get { return Entities.Roles; }
        }

        /// <summary>
        /// Активные роли
        /// </summary>
        public static IQueryable<Roles> RolesActive
        {
            get
            {
                return
                    Roles.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedRolesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (Roles item in Roles)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdRole;
                listItem.ParentCollection = Roles;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.RoleNameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.RoleNameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить роль по Id
        /// </summary>
        /// <param name="idRole">Id роли</param>
        /// <returns>роль</returns>
        public static Roles GetRolebyId(int idRole)
        {
            Roles _result = null;
            foreach (Roles role in Roles)
            {
                if (role.IdRole == idRole)
                {
                    _result = role;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление роли
        /// </summary>
        /// <param name="roleItem">роль</param>
        public static void RolesUpdate(Roles roleItem)
        {
            if (roleItem != null)
            {
                Roles roleUpdate = GetRolebyId(roleItem.IdRole);
                if (roleUpdate != null)
                {
                    roleUpdate.IsActive = roleItem.IsActive;
                    roleUpdate.IdProfineRegion = roleItem.IdProfineRegion;
                    roleUpdate.RoleNameRu = roleItem.RoleNameRu;
                    roleUpdate.RoleNameEn = roleItem.RoleNameEn;
                    roleUpdate.IdRolesType = roleItem.IdRolesType;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление роли
        /// </summary>
        /// <param name="roleItem">роль</param>
        public static void RolesInsert(Roles roleItem)
        {
            Entities.Roles.AddObject(roleItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление роли
        /// </summary>
        /// <param name="roleItem">рольа</param>
        public static void RolesDelete(Roles roleItem)
        {
            if (roleItem != null)
            {
                Roles roleDel = GetRolebyId(roleItem.IdRole);
                if (roleDel != null)
                {
                    Roles.DeleteObject(roleDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region GlassUnitMarks

        /// <summary>
        /// Список стеклопакетов
        /// </summary>
        public static ObjectSet<GlassUnitMarks> GlassUnitMarks
        {
            get { return Entities.GlassUnitMarks; }
        }

        /// <summary>
        /// Активные стеклопакеты
        /// </summary>
        public static IQueryable<GlassUnitMarks> GlassUnitMarksActive
        {
            get
            {
                return
                    GlassUnitMarks.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получить стеклопакет по Id
        /// </summary>
        /// <param name="idGlassUnitMark">Id стеклопакета</param>
        /// <returns>стеклопакет</returns>
        public static GlassUnitMarks GetGlassUnitMarkbyId(int idGlassUnitMark)
        {
            GlassUnitMarks _result = null;
            foreach (GlassUnitMarks glassUnitMark in GlassUnitMarks)
            {
                if (glassUnitMark.IdGlassUnitMark == idGlassUnitMark)
                {
                    _result = glassUnitMark;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление стеклопакета
        /// </summary>
        /// <param name="glassUnitMarkItem">стеклопакет</param>
        public static void GlassUnitMarksUpdate(GlassUnitMarks glassUnitMarkItem)
        {
            if (glassUnitMarkItem != null)
            {
                GlassUnitMarks glassUnitMarkUpdate = GetGlassUnitMarkbyId(glassUnitMarkItem.IdGlassUnitMark);
                if (glassUnitMarkUpdate != null)
                {
                    glassUnitMarkUpdate.IsActive = glassUnitMarkItem.IsActive;
                    glassUnitMarkUpdate.GlassUnitMark = glassUnitMarkItem.GlassUnitMark;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление стеклопакета
        /// </summary>
        /// <param name="glassUnitMarkItem">стеклопакет</param>
        public static void GlassUnitMarksInsert(GlassUnitMarks glassUnitMarkItem)
        {
            Entities.GlassUnitMarks.AddObject(glassUnitMarkItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление стеклопакета
        /// </summary>
        /// <param name="glassUnitMarkItem">стеклопакет</param>
        public static void GlassUnitMarksDelete(GlassUnitMarks glassUnitMarkItem)
        {
            if (glassUnitMarkItem != null)
            {
                GlassUnitMarks glassUnitMarkDel = GetGlassUnitMarkbyId(glassUnitMarkItem.IdGlassUnitMark);
                if (glassUnitMarkDel != null)
                {
                    GlassUnitMarks.DeleteObject(glassUnitMarkDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region FurnitureMarks

        /// <summary>
        /// Список форнитур
        /// </summary>
        public static ObjectSet<FurnitureMarks> FurnitureMarks
        {
            get { return Entities.FurnitureMarks; }
        }

        /// <summary>
        /// Активные форнитуры
        /// </summary>
        public static IQueryable<FurnitureMarks> FurnitureMarksActive
        {
            get
            {
                return
                    FurnitureMarks.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получить форнитуру по Id
        /// </summary>
        /// <param name="idFurnitureMark">Id форнитуры</param>
        /// <returns>форнитура</returns>
        public static FurnitureMarks GetFurnitureMarkbyId(int idFurnitureMark)
        {
            FurnitureMarks _result = null;
            foreach (FurnitureMarks furnitureMark in FurnitureMarks)
            {
                if (furnitureMark.IdFurnitureMark == idFurnitureMark)
                {
                    _result = furnitureMark;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление форнитуры
        /// </summary>
        /// <param name="furnitureMarkItem">форнитура</param>
        public static void FurnitureMarksUpdate(FurnitureMarks furnitureMarkItem)
        {
            if (furnitureMarkItem != null)
            {
                FurnitureMarks furnitureMarkUpdate = GetFurnitureMarkbyId(furnitureMarkItem.IdFurnitureMark);
                if (furnitureMarkUpdate != null)
                {
                    furnitureMarkUpdate.IsActive = furnitureMarkItem.IsActive;
                    furnitureMarkUpdate.FurnitureMark = furnitureMarkItem.FurnitureMark;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление форнитуры
        /// </summary>
        /// <param name="furnitureMarkItem">форнитура</param>
        public static void FurnitureMarksInsert(FurnitureMarks furnitureMarkItem)
        {
            Entities.FurnitureMarks.AddObject(furnitureMarkItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление форнитуры
        /// </summary>
        /// <param name="furnitureMarkItem">форнитура</param>
        public static void FurnitureMarksDelete(FurnitureMarks furnitureMarkItem)
        {
            if (furnitureMarkItem != null)
            {
                FurnitureMarks furnitureMarkDel = GetFurnitureMarkbyId(furnitureMarkItem.IdFurnitureMark);
                if (furnitureMarkDel != null)
                {
                    FurnitureMarks.DeleteObject(furnitureMarkDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Vendors

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedToolsVendors(string culture)
        {
            return null;
        }

        /// <summary>
        /// Список производителей
        /// </summary>
        public static ObjectSet<Vendors> Vendors
        {
            get { return Entities.Vendors; }
        }

        /// <summary>
        /// Активные производители
        /// </summary>
        public static IQueryable<Vendors> VendorsActive
        {
            get
            {
                return
                    Vendors.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получить производителя по Id
        /// </summary>
        /// <param name="idVendor">Id производителя</param>
        /// <returns>производитель</returns>
        public static Vendors GetVendorbyId(int idVendor)
        {
            Vendors _result = null;
            foreach (Vendors vendor in Vendors)
            {
                if (vendor.IdVendor == idVendor)
                {
                    _result = vendor;
                    break;
                }
            }
            return _result;
        }

        public static List<Vendors> GetVendorsByVendorsTypeId(int vendorTypeId)
        {
            List<Vendors> result = null;

            foreach (Vendors vendor in Vendors)
            {
                foreach (VendorsVendorsTypes VendorType in vendor.VendorsVendorsTypes)
                {
                    if (VendorType.IdVendorsType == vendorTypeId)
                    {
                        if (result == null)
                            result = new List<Vendors>();
                        if (!result.Contains(vendor)) result.Add(vendor);
                        break;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// Обновление производителя
        /// </summary>
        /// <param name="vendorItem">производитель</param>
        public static void VendorsUpdate(Vendors vendorItem)
        {
            if (vendorItem != null)
            {
                Vendors vendorUpdate = GetVendorbyId(vendorItem.IdVendor);
                if (vendorUpdate != null)
                {
                    vendorUpdate.IsActive = vendorItem.IsActive;
                    vendorUpdate.VendorName = vendorItem.VendorName;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление производителя
        /// </summary>
        /// <param name="vendorItem">производитель</param>
        public static void VendorsInsert(Vendors vendorItem)
        {
            Entities.Vendors.AddObject(vendorItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление производителя
        /// </summary>
        /// <param name="vendorItem">производитель</param>
        public static void VendorsDelete(Vendors vendorItem)
        {
            if (vendorItem != null)
            {
                Vendors vendorDel = GetVendorbyId(vendorItem.IdVendor);
                if (vendorDel != null)
                {
                    Vendors.DeleteObject(vendorDel);
                    DB.Save();
                }
            }
        }


        /// <summary>
        /// Производители оборудования
        /// </summary>
        public static List<Vendors> EquipmentVendors
        {
            get
            {
                List<Vendors> result = new List<Vendors>();
                foreach (var item in VendorsActive)
                {
                    foreach (var type in item.VendorsVendorsTypes)
                    {
                        if (type.IdVendorsType == 4)
                        {
                            result.Add(item);
                        }
                    }
                }
                return result;
            }
        }

        #endregion

        #region VendorsTypes

        /// <summary>
        /// Список типов производителей
        /// </summary>
        public static ObjectSet<VendorsTypes> VendorsTypes
        {
            get { return Entities.VendorsTypes; }
        }

        /// <summary>
        /// Активные типы производителей
        /// </summary>
        public static IQueryable<VendorsTypes> VendorsTypesActive
        {
            get
            {
                return
                    VendorsTypes.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка типов производителей
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedVendorsTypesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (VendorsTypes item in VendorsTypes)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdVendorsType;
                listItem.ParentCollection = VendorsTypes;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.VendorsTypeNameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.VendorsTypeNameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить тип производителя по Id
        /// </summary>
        /// <param name="idVendorsType">Id типа производителя</param>
        /// <returns>тип производителя</returns>
        public static VendorsTypes GetVendorsTypebyId(int idVendorsType)
        {
            VendorsTypes _result = null;
            foreach (VendorsTypes vendorsType in VendorsTypes)
            {
                if (vendorsType.IdVendorsType == idVendorsType)
                {
                    _result = vendorsType;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление типа производителя
        /// </summary>
        /// <param name="vendorsTypeItem">тип производителя</param>
        public static void VendorsTypesUpdate(VendorsTypes vendorsTypeItem)
        {
            if (vendorsTypeItem != null)
            {
                VendorsTypes vendorsTypeUpdate = GetVendorsTypebyId(vendorsTypeItem.IdVendorsType);
                if (vendorsTypeUpdate != null)
                {
                    vendorsTypeUpdate.IsActive = vendorsTypeItem.IsActive;
                    vendorsTypeUpdate.VendorsTypeNameEn = vendorsTypeItem.VendorsTypeNameEn;
                    vendorsTypeUpdate.VendorsTypeNameRu = vendorsTypeItem.VendorsTypeNameRu;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление типа производителя
        /// </summary>
        /// <param name="vendorsTypeItem">тип производителя</param>
        public static void VendorsTypesInsert(VendorsTypes vendorsTypeItem)
        {
            Entities.VendorsTypes.AddObject(vendorsTypeItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление типа производителя
        /// </summary>
        /// <param name="vendorsTypeItem">тип производителя</param>
        public static void VendorsTypesDelete(VendorsTypes vendorsTypeItem)
        {
            if (vendorsTypeItem != null)
            {
                VendorsTypes vendorsTypeDel = GetVendorsTypebyId(vendorsTypeItem.IdVendorsType);
                if (vendorsTypeDel != null)
                {
                    VendorsTypes.DeleteObject(vendorsTypeDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region EquipmentTypesVendorsTypes

        /// <summary>
        /// Список типов производителей
        /// </summary>
        public static ObjectSet<EquipmentTypesVendorTypes> EquipmentTypesVendorTypes
        {
            get { return Entities.EquipmentTypesVendorTypes; }
        }

        /// <summary>
        /// Активные типы производителей
        /// </summary>
        public static IQueryable<EquipmentTypesVendorTypes> EquipmentTypesVendorTypesActive
        {
            get
            {
                return
                    EquipmentTypesVendorTypes.Where(p => p.IsActive);
            }
        }


        /// <summary>
        /// Поиск связки по идентификатору
        /// </summary>
        /// <param name="id">Идентификатор</param>
        /// <returns>Связка</returns>
        public static EquipmentTypesVendorTypes GetEquipmentTypesVendorTypesById(int id)
        {
            return EquipmentTypesVendorTypes.SingleOrDefault(p => p.IdEquipmentTypesVendorsTypes == id);
        }


        /// <summary>
        /// Обновление типа производителя
        /// </summary>
        public static void EquipmentTypesVendorTypesUpdate(EquipmentTypesVendorTypes equipmentTypesVendorTypesItem)
        {
            if (equipmentTypesVendorTypesItem != null)
            {
                EquipmentTypesVendorTypes vendorsTypeUpdate = GetEquipmentTypesVendorTypesById(equipmentTypesVendorTypesItem.IdEquipmentTypesVendorsTypes);
                if (vendorsTypeUpdate != null)
                {
                    vendorsTypeUpdate.IsActive = equipmentTypesVendorTypesItem.IsActive;
                    vendorsTypeUpdate.IdEquipmentType = equipmentTypesVendorTypesItem.IdEquipmentType;
                    vendorsTypeUpdate.IdVendorType = equipmentTypesVendorTypesItem.IdVendorType;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление типа производителя
        /// </summary>
        /// <param name="vendorsTypeItem">тип производителя</param>
        public static void EquipmentTypesVendorTypesInsert(EquipmentTypesVendorTypes vendorsTypeItem)
        {
            Entities.EquipmentTypesVendorTypes.AddObject(vendorsTypeItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление типа производителя
        /// </summary>
        /// <param name="vendorsTypeItem">тип производителя</param>
        public static void EquipmentTypesVendorTypesDelete(EquipmentTypesVendorTypes vendorsTypeItem)
        {
            if (vendorsTypeItem != null)
            {
                EquipmentTypesVendorTypes vendorsTypeDel = GetEquipmentTypesVendorTypesById(vendorsTypeItem.IdEquipmentTypesVendorsTypes);
                if (vendorsTypeDel != null)
                {
                    EquipmentTypesVendorTypes.DeleteObject(vendorsTypeDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region Turnovers

        /// <summary>
        /// Список оборотов
        /// </summary>
        public static ObjectSet<Turnovers> Turnovers
        {
            get { return Entities.Turnovers; }
        }

        /// <summary>
        /// Активные обороты
        /// </summary>
        public static ObjectSet<Turnovers> TurnoversActive
        {
            get
            {
                return
                    // (List<Turnovers>) Turnovers.Where(q => q.TurnoverClassifications.IsActive);
                    Turnovers;
            }
        }

        /// <summary>
        /// Получить оборот по Id
        /// </summary>
        /// <param name="idTurnover">Id оборота</param>
        /// <returns>оборот</returns>
        public static Turnovers GetTurnoverbyId(int idTurnover)
        {
            Turnovers _result = null;
            foreach (Turnovers turnover in Turnovers)
            {
                if (turnover.IdTurnover == idTurnover)
                {
                    _result = turnover;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление оборота
        /// </summary>
        /// <param name="turnoverItem">оборот</param>
        public static void TurnoversUpdate(Turnovers turnoverItem)
        {
            if (turnoverItem != null)
            {
                Turnovers turnoverUpdate = GetTurnoverbyId(turnoverItem.IdTurnover);
                if (turnoverUpdate != null)
                {
                    turnoverUpdate.Amount = turnoverItem.Amount;
                    turnoverUpdate.Period = turnoverItem.Period;
                    turnoverUpdate.IdLegalEntity = turnoverItem.IdLegalEntity;
                    turnoverUpdate.IdDealerLegalEntity = turnoverItem.IdDealerLegalEntity;
                    turnoverUpdate.IdTurnoverClassification = turnoverItem.IdTurnoverClassification;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление оборота
        /// </summary>
        /// <param name="turnoverItem">оборот</param>
        /// <param name="userLogin"></param>
        public static void TurnoversInsert(Turnovers turnoverItem, string userLogin)
        {
            if (!string.IsNullOrEmpty(userLogin))
            {
                turnoverItem.IdUser = userLogin;
                Entities.Turnovers.AddObject(turnoverItem);
                DB.Save();
            }
        }

        /// <summary>
        /// Удаление оборот
        /// </summary>
        /// <param name="turnoverItem">оборота</param>
        public static void TurnoversDelete(Turnovers turnoverItem)
        {
            if (turnoverItem != null)
            {
                Turnovers turnoverDel = GetTurnoverbyId(turnoverItem.IdTurnover);
                if (turnoverDel != null)
                {
                    Entities.Turnovers.DeleteObject(turnoverDel);
                    DB.Save();
                }
            }
        }


        /// <summary>
        /// Список оборотов новичков
        /// </summary>
        /// <returns></returns>
        //public static IEnumerable<Turnovers> GetNoviciesTurnovers(string userLogin)
        //{
        //    var result = new List<Turnovers>();

        //    //var tempCol = from t in GetTurnoversByUser(userLogin) orderby t.Period select t;

        //    foreach (var le in LegalEntities)
        //    {
        //        var turnover = le.FirstTurnover;
        //        if (turnover != null) result.Add(le.FirstTurnover);
        //    }


        //    return result;
        //}

        /// <summary>
        /// Возвращает список оборотов определенного периода
        /// </summary>
        /// <param name="period"></param>
        /// <param name="turnovers"></param>
        /// <returns>список оборотов</returns>
        public static List<Turnovers> GetTurnoversByPeriod(DateTime period, List<Turnovers> turnovers)
        {
            return turnovers.Where(turnover => turnover.Period == period).ToList();
        }

        /// <summary>
        /// Возвращает список оборотов которые попадают в заданное окно дат.
        /// </summary>
        /// <param name="beginDate"></param>
        /// <param name="endDate"></param>
        /// <param name="turnovers"></param>
        /// <returns>список оборотов</returns>
        public static List<Turnovers> GetTurnoversBetweenDates(DateTime beginDate, DateTime endDate, List<Turnovers> turnovers)
        {
            List<Turnovers> resultList = new List<Turnovers>();
            foreach (var turnover in turnovers)
            {
                if (turnover.Period >= beginDate && turnover.Period <= endDate)
                {
                    resultList.Add(turnover);
                }
            }
            return resultList;
        }


        ///// <summary>
        ///// Применение фильтра к коллекции оборотов
        ///// </summary>
        ///// <param name="filterItem">Фильтр</param>
        ///// <param name="turnoversCollection">Коллекция оборотов (опционально)</param>
        ///// <returns>Отфильтрованная коллекция оборотов</returns>
        //public static List<Turnovers> GetTurnoversByFilterItem(FilterItem filterItem, List<Turnovers> turnoversCollection = null)
        //{
        //    // List<Turnovers> result = new List<Turnovers>();

        //    List<Turnovers> innerTurnoversCollection;
        //    if (turnoversCollection == null)
        //    {
        //        innerTurnoversCollection = DB.Turnovers.ToList();
        //    }
        //    else
        //    {
        //        innerTurnoversCollection = turnoversCollection;
        //    }

        //    if (filterItem.IdProfineRegion != 0)
        //    {
        //        innerTurnoversCollection = GetTurnoversByRegionId(filterItem.IdProfineRegion, innerTurnoversCollection);
        //    }

        //    innerTurnoversCollection = GetTurnoversBetweenDates(filterItem.PeriodStart, filterItem.PeriodEnd,
        //                                                        innerTurnoversCollection);

        //    if (!string.IsNullOrEmpty(filterItem.IdManager))
        //    {
        //        innerTurnoversCollection = GetTurnoversByIdManager(filterItem.IdManager, innerTurnoversCollection);
        //    }

        //    return innerTurnoversCollection;
        //}


        /// <summary>
        /// Фильтрация оборотов по менеджеру
        /// </summary>
        /// <param name="idManager">Идентификатор менеджера</param>
        /// <param name="turnovers">Коллекция оборотов</param>
        /// <returns>Отфильтрованнная коллекция</returns>
        private static List<Turnovers> GetTurnoversByIdManager(string idManager, List<Turnovers> turnovers = null)
        {
            List<Turnovers> result;

            if (turnovers != null)
            {
                result = turnovers;
            }
            else
            {
                result = DB.Turnovers.ToList();
            }


            return result.Where(item => item.LegalEntities.Customers.IdManagerSTR == idManager).ToList();
        }


        /// <summary>
        /// Получение списка юридических лиц из списка оборотов
        /// </summary>
        /// <param name="turnovers">Список оборотов</param>
        /// <returns>Список юридических лиц</returns>
        public static List<LegalEntities> GetLegalEntitiesFromTurnovers(IEnumerable<Turnovers> turnovers)
        {
            List<LegalEntities> result = new List<LegalEntities>();

            if (turnovers != null)
                foreach (var turnover in turnovers)
                {
                    if (!result.Contains(turnover.LegalEntities))
                    {
                        result.Add(turnover.LegalEntities);
                    }
                }

            return result;
        }

        //public static List<LegalEntities> GetDealerLegalEntitiesFromTurnovers(IEnumerable<Turnovers> turnovers)
        //{
        //    List<LegalEntities> result = new List<LegalEntities>();

        //    foreach (var turnover in turnovers)
        //    {
        //        if (!result.Contains(turnover.DealerLegalEntity))
        //        {
        //            result.Add(turnover.DealerLegalEntity);
        //        }
        //    }

        //    return result;
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="idRegion"></param>
        /// <param name="turnovers"></param>
        /// <returns></returns>
        //public static List<Turnovers> GetTurnoversByRegionId(int idRegion, List<Turnovers> turnovers)
        //{
        //    List<Turnovers> resultList = new List<Turnovers>();

        //    foreach (var item in turnovers)
        //    {
        //        if (item.IdProfineRegion == idRegion)
        //            resultList.Add(item);
        //    }

        //    return resultList;
        //}

        /// <summary>
        /// недописанная
        /// </summary>
        /// <param name="profineRegion"></param>
        /// <returns></returns>
        public static List<Turnovers> GetTurnoversByLegalEntity(profineRegions profineRegion, List<Turnovers> turnovers)
        {
            List<Turnovers> resultList = new List<Turnovers>();
            foreach (var turnover in turnovers)
            {
                Customers customer = GetCustomerById(turnover.LegalEntities.IdCustomer);
            }


            return resultList;
        }

        /// <summary>
        /// Формирует список оборотов, доступных пользователю Windows на основании региона пользователя.
        /// </summary>
        /// <param name="user">пользователь Windows</param>
        /// <param name="turnovers">необязательный список оборотов</param>
        /// <returns>список оборотов</returns>
        public static IEnumerable<Turnovers> GetTurnoversByUser(string userLogin, IEnumerable<Turnovers> turnovers = null)
        {
            var result = new List<Turnovers>();

            if (turnovers == null)
                turnovers = DB.Turnovers;
            // return Turnovers;
            if (userLogin != null)
            {
                //  result.AddRange(turnovers.Where(turnoverItem => PermissionsManager.ValidateUserAndTurnover(user, turnoverItem)));

                Users user = GetUserByLogin(userLogin);

                if (user != null)
                {
                    foreach (var item in turnovers)
                    {
                        //if (PermissionsManager.ValidateUserAndTurnover(user, item))
                        //{
                        //    result.Add(item);
                        //}
                    }
                }
            }

            return result;
        }

        #endregion

        #region TurnoverClassifications

        /// <summary>
        /// Список классификаций оборотов
        /// </summary>
        public static ObjectSet<TurnoverClassifications> TurnoverClassifications
        {
            get { return Entities.TurnoverClassifications; }
        }

        /// <summary>
        /// Активные классификации оборота
        /// </summary>
        public static IQueryable<TurnoverClassifications> TurnoverClassificationsActive
        {
            get
            {
                return
                    TurnoverClassifications.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedTurnoverClassificationsNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (TurnoverClassifications item in TurnoverClassifications)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdTurnoverClassification;
                listItem.ParentCollection = TurnoverClassifications;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.TurnoverClassificationRu;
                }
                else
                {
                    listItem.LocaLizedString = item.TurnoverClassificationEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить классификацию оборота по Id
        /// </summary>
        /// <param name="idTurnoverClassification">Id классификации оборота</param>
        /// <returns>классификация оборота</returns>
        public static TurnoverClassifications GetTurnoverClassificationbyId(int idTurnoverClassification)
        {
            TurnoverClassifications _result = null;
            foreach (TurnoverClassifications turnoverClassification in TurnoverClassifications)
            {
                if (turnoverClassification.IdTurnoverClassification == idTurnoverClassification)
                {
                    _result = turnoverClassification;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление классификации оборота
        /// </summary>
        /// <param name="turnoverClassificationItem">классификация оборота</param>
        public static void TurnoverClassificationsUpdate(TurnoverClassifications turnoverClassificationItem)
        {
            if (turnoverClassificationItem != null)
            {
                TurnoverClassifications turnoverClassificationUpdate =
                    GetTurnoverClassificationbyId(turnoverClassificationItem.IdTurnoverClassification);
                if (turnoverClassificationUpdate != null)
                {
                    turnoverClassificationUpdate.IsActive = turnoverClassificationItem.IsActive;
                    turnoverClassificationUpdate.TurnoverClassificationEn =
                        turnoverClassificationItem.TurnoverClassificationEn;
                    turnoverClassificationUpdate.TurnoverClassificationRu =
                        turnoverClassificationItem.TurnoverClassificationRu;
                    turnoverClassificationUpdate.IdParent = turnoverClassificationItem.IdParent;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление площадки
        /// </summary>
        /// <param name="turnoverClassificationItem">площадка</param>
        public static void TurnoverClassificationsInsert(TurnoverClassifications turnoverClassificationItem)
        {
            Entities.TurnoverClassifications.AddObject(turnoverClassificationItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление классификации оборота
        /// </summary>
        /// <param name="turnoverClassificationItem">классификация оборота</param>
        public static void TurnoverClassificationsDelete(TurnoverClassifications turnoverClassificationItem)
        {
            if (turnoverClassificationItem != null)
            {
                TurnoverClassifications turnoverClassificationDel =
                    GetTurnoverClassificationbyId(turnoverClassificationItem.IdTurnoverClassification);
                if (turnoverClassificationDel != null)
                {
                    TurnoverClassifications.DeleteObject(turnoverClassificationDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region DistributionChannelTypes

        /// <summary>
        /// Список типов каналов продаж
        /// </summary>
        public static ObjectSet<DistributionChannelTypes> DistributionChannelTypes
        {
            get { return Entities.DistributionChannelTypes; }
        }

        /// <summary>
        /// Активные типы каналов продаж
        /// </summary>
        public static IQueryable<DistributionChannelTypes> DistributionChannelTypesActive
        {
            get
            {
                return
                    DistributionChannelTypes.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного типов каналов продаж
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedDistributionChannelTypesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (DistributionChannelTypes item in DistributionChannelTypes)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdDistributionChannelType;
                listItem.ParentCollection = DistributionChannelTypes;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.DistributionChannelTypeRu;
                }
                else
                {
                    listItem.LocaLizedString = item.DistributionChannelTypeEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить тип канала продаж по Id
        /// </summary>
        /// <param name="idDistributionChannelType">Id типа канала продаж</param>
        /// <returns>тип канала продаж</returns>
        public static DistributionChannelTypes GetDistributionChannelTypebyId(int idDistributionChannelType)
        {
            DistributionChannelTypes _result = null;
            foreach (DistributionChannelTypes distributionChannelType in DistributionChannelTypes)
            {
                if (distributionChannelType.IdDistributionChannelType == idDistributionChannelType)
                {
                    _result = distributionChannelType;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление типа канала продаж
        /// </summary>
        /// <param name="distributionChannelTypeItem">тип канала продаж</param>
        public static void DistributionChannelTypesUpdate(DistributionChannelTypes distributionChannelTypeItem)
        {
            if (distributionChannelTypeItem != null)
            {
                DistributionChannelTypes distributionChannelTypeUpdate =
                    GetDistributionChannelTypebyId(distributionChannelTypeItem.IdDistributionChannelType);
                if (distributionChannelTypeUpdate != null)
                {
                    distributionChannelTypeUpdate.IsActive = distributionChannelTypeItem.IsActive;
                    distributionChannelTypeUpdate.DistributionChannelTypeRu =
                        distributionChannelTypeItem.DistributionChannelTypeRu;
                    distributionChannelTypeUpdate.DistributionChannelTypeEn =
                        distributionChannelTypeItem.DistributionChannelTypeEn;
                    //  distributionChannelTypeUpdate.IdUser = IdUser;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление типа канала продаж
        /// </summary>
        /// <param name="distributionChannelTypeItem">тип канала продаж</param>
        public static void DistributionChannelTypesInsert(DistributionChannelTypes distributionChannelTypeItem)
        {
            //  distributionChannelTypeItem.IdUser = IdUser;

            if (distributionChannelTypeItem.DistributionChannelTypeEn == null)
                distributionChannelTypeItem.DistributionChannelTypeEn = "-";
            if (distributionChannelTypeItem.DistributionChannelTypeRu == null)
                distributionChannelTypeItem.DistributionChannelTypeRu = "-";

            Entities.DistributionChannelTypes.AddObject(distributionChannelTypeItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление типа канала продаж
        /// </summary>
        /// <param name="distributionChannelTypeItem">тип канала продаж</param>
        public static void DistributionChannelTypesDelete(DistributionChannelTypes distributionChannelTypeItem)
        {
            if (distributionChannelTypeItem != null)
            {
                DistributionChannelTypes distributionChannelTypeDel =
                    GetDistributionChannelTypebyId(distributionChannelTypeItem.IdDistributionChannelType);
                if (distributionChannelTypeDel != null)
                {
                    DistributionChannelTypes.DeleteObject(distributionChannelTypeDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region DistributionChannels

        /// <summary>
        /// Список каналов продаж
        /// </summary>
        public static ObjectSet<DistributionChannels> DistributionChannels
        {
            get { return Entities.DistributionChannels; }
        }

        /// <summary>
        /// Активные каналы продаж
        /// </summary>
        public static IQueryable<DistributionChannels> DistributionChannelsActive
        {
            get
            {
                return
                    DistributionChannels.Where(p => p.IsActive).
                        Where(q => q.DistributionChannelTypes.IsActive).
                        Where(d => d.Customers.IsActive == true);
            }
        }

        /// <summary>
        /// Получить канал продаж по Id
        /// </summary>
        /// <param name="idDistributionChannel">Id канала продаж</param>
        /// <returns>канал продаж</returns>
        public static DistributionChannels GetDistributionChannelbyId(int idDistributionChannel)
        {
            DistributionChannels _result = null;
            foreach (DistributionChannels distributionChannel in DistributionChannels)
            {
                if (distributionChannel.IdDistributionChannel == idDistributionChannel)
                {
                    _result = distributionChannel;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление канала продаж
        /// </summary>
        /// <param name="distributionChannelItem">канал продаж</param>
        public static void DistributionChannelsUpdate(DistributionChannels distributionChannelItem)
        {
            if (distributionChannelItem != null)
            {
                DistributionChannels distributionChannelUpdate =
                    GetDistributionChannelbyId(distributionChannelItem.IdDistributionChannel);
                if (distributionChannelUpdate != null)
                {
                    distributionChannelUpdate.IsActive = distributionChannelItem.IsActive;
                    distributionChannelUpdate.IdCustomer = distributionChannelItem.IdCustomer;
                    distributionChannelUpdate.IdDistributionChannelType =
                        distributionChannelItem.IdDistributionChannelType;
                    distributionChannelUpdate.Period = distributionChannelItem.Period;
                    distributionChannelUpdate.Amount = distributionChannelItem.Amount;
                    //    distributionChannelUpdate.IdUser = IdUser;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление канала продаж
        /// </summary>
        /// <param name="distributionChannelItem">канал продаж</param>
        public static void DistributionChannelsInsert(DistributionChannels distributionChannelItem)
        {
            Entities.DistributionChannels.AddObject(distributionChannelItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление канала продаж
        /// </summary>
        /// <param name="distributionChannelItem">канал продаж</param>
        public static void DistributionChannelsDelete(DistributionChannels distributionChannelItem)
        {
            if (distributionChannelItem != null)
            {
                DistributionChannels distributionChannelDel =
                    GetDistributionChannelbyId(distributionChannelItem.IdDistributionChannel);
                if (distributionChannelDel != null)
                {
                    DistributionChannels.DeleteObject(distributionChannelDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region CustomersProductsSystems

        /// <summary>
        /// Список CustomersProductsSystems
        /// </summary>
        public static ObjectSet<CustomersProductsSystems> CustomersProductsSystems
        {
            get { return Entities.CustomersProductsSystems; }
        }

        /// <summary>
        /// Активные CustomersProductsSystem
        /// </summary>
        public static IQueryable<CustomersProductsSystems> CustomersProductsSystemsActive
        {
            get
            {
                return
                    CustomersProductsSystems.Where(p => p.IsActive).
                        Where(q => q.Customers.IsActive == true).
                        Where(d => d.ProductSystems.IsActive == true);
            }
        }

        /// <summary>
        /// Получить CustomersProductsSystem по Id
        /// </summary>
        /// <param name="idCustomersProductsSystem">Id CustomersProductsSystem</param>
        /// <returns>CustomersProductsSystem</returns>
        public static CustomersProductsSystems GetCustomersProductsSystembyId(int idCustomersProductsSystem)
        {
            CustomersProductsSystems _result = null;
            foreach (CustomersProductsSystems customersProductsSystem in CustomersProductsSystems)
            {
                if (customersProductsSystem.IdCustomersProductsSystem == idCustomersProductsSystem)
                {
                    _result = customersProductsSystem;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление CustomersProductsSystem
        /// </summary>
        /// <param name="customersProductsSystemItem">CustomersProductsSystem</param>
        public static void CustomersProductsSystemsUpdate(CustomersProductsSystems customersProductsSystemItem)
        {
            if (customersProductsSystemItem != null)
            {
                CustomersProductsSystems customersProductsSystemUpdate =
                    GetCustomersProductsSystembyId(customersProductsSystemItem.IdCustomersProductsSystem);
                if (customersProductsSystemUpdate != null)
                {
                    customersProductsSystemUpdate.IsActive = customersProductsSystemItem.IsActive;
                    customersProductsSystemUpdate.IdProductSystem = customersProductsSystemItem.IdProductSystem;
                    customersProductsSystemUpdate.IdCustomer = customersProductsSystemItem.IdCustomer;
                    customersProductsSystemUpdate.Period = customersProductsSystemItem.Period;
                    customersProductsSystemUpdate.Amount = customersProductsSystemItem.Amount;
                    //  customersProductsSystemUpdate.IdUser = IdUser;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление CustomersProductsSystem
        /// </summary>
        /// <param name="customersProductsSystemItem">CustomersProductsSystem</param>
        public static void CustomersProductsSystemsInsert(CustomersProductsSystems customersProductsSystemItem)
        {
            Entities.CustomersProductsSystems.AddObject(customersProductsSystemItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление CustomersProductsSystem
        /// </summary>
        /// <param name="customersProductsSystemItem">CustomersProductsSystem</param>
        public static void CustomersProductsSystemsDelete(CustomersProductsSystems customersProductsSystemItem)
        {
            if (customersProductsSystemItem != null)
            {
                CustomersProductsSystems customersProductsSystemDel =
                    GetCustomersProductsSystembyId(customersProductsSystemItem.IdCustomersProductsSystem);
                if (customersProductsSystemDel != null)
                {
                    CustomersProductsSystems.DeleteObject(customersProductsSystemDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region LegalEntities

        /// <summary>
        /// Получение юр. лиц а по идентификатору
        /// </summary>
        /// <param name="idLegalEntity">Идентификатор</param>
        /// <returns>Юр. лицо</returns>
        public static LegalEntities GetLegalEntityById(int idLegalEntity)
        {
            return LegalEntities.Single(p => p.IdLegalEntity == idLegalEntity);
        }

        /// <summary>
        /// Список юр. лиц
        /// </summary>
        public static IQueryable<LegalEntities> LegalEntities
        {
            get { return DB.Entities.LegalEntities; }
        }

        /// <summary>
        /// Возвращает список юр. лиц, содержащих в названии строку символов
        /// </summary>
        /// <param name="word"></param>
        /// <param name="exactName"></param>
        /// <returns></returns>
        public static List<LegalEntities> GetLegalEntitiesContainedString(string word = "/", bool exactName = false)
        {
            var result = new List<LegalEntities>();
            if (!exactName)
            {
                foreach (var legalEntity in LegalEntities)
                {
                    if (legalEntity.Name.Contains(word))
                        result.Add(legalEntity);
                }
            }
            else
            {
                foreach (var legalEntity in LegalEntities)
                {
                    if (legalEntity.Name.ToUpper().Trim().Contains(word.ToUpper().Trim()))
                        result.Add(legalEntity);
                }
            }
            return result;
        }

        //public static void SplitLegalEntities()
        //{
        //    var col = GetLegalEntitiesContainedString();
        //    foreach (var item in col)
        //    {

        //        string[] names = item.Name.Split('/');

        //        item.Name = names[0];

        //        for (int i = 1; i < names.Length; i++)
        //        {
        //            var newItem = new LegalEntities();
        //            newItem.Name = names[i];
        //            newItem.IdCustomer = item.IdCustomer;
        //            newItem.NumberInSAP = item.NumberInSAP;

        //            item.Customers.AddLegalEntity(newItem, "28prygun01");
        //        }

        //    }
        //}

        #endregion

        #region Contacts


        /// <summary>
        /// Коллекция всех контактов
        /// </summary>
        public static IEnumerable<Contacts> Contacts
        {
            get { return DB.Entities.Contacts; }
        }


        /// <summary>
        /// Получение контакта по Id
        /// </summary>
        /// <param name="idContact">Идентификатор</param>
        /// <returns>Контакт</returns>
        public static Contacts GetContactById(int idContact)
        {
            return Contacts.Single(p => p.IdContact == idContact);
        }

        #endregion

        #region UsersInRoles

        /// <summary>
        /// Список площадок
        /// </summary>
        public static ObjectSet<UsersInRoles> UsersInRoles
        {
            get { return Entities.UsersInRoles; }
        }

        /// <summary>
        /// Активные площадки
        /// </summary>
        //public static IQueryable<UsersInRoles> UsersInRolesActive
        //{
        //    get
        //    {
        //        return
        //            UsersInRoles.Where(p => p.IsActive).Where(q => q.TrainingsCenters.IsActive);
        //    }
        //}



        /// <summary>
        /// Получить площадку по Id
        /// </summary>
        /// <param name="idUsersInRole">Id площадки</param>
        /// <returns>площадка</returns>
        public static UsersInRoles GetUsersInRolebyId(int idUsersInRole)
        {
            return Enumerable.FirstOrDefault(UsersInRoles, usersInRole => usersInRole.IdUsersInRole == idUsersInRole);
        }

        /// <summary>
        /// Ищет роли, которым принадлежит данный пользователь
        /// </summary>
        /// <param name="userLoginName">имя пользователя</param>
        /// <returns>список ролей</returns>
        public static List<Roles> GetRolesByUserLoginname(string userLoginName)
        {
            List<Roles> result = new List<Roles>();
            Users user = GetUserByLogin(userLoginName);
            foreach (var item in user.UsersInRoles)
            {
                result.Add(item.Roles);
            }

            return result;
        }




        /// <summary>
        /// Получение списка ролей пользователя
        /// </summary>
        /// <param name="user">Пользователь</param>
        /// <returns>Список ролей</returns>
        public static List<Roles> GetRolesByUser(Users user)
        {
            List<Roles> result = new List<Roles>();
            foreach (var item in user.UsersInRoles)
            {
                result.Add(item.Roles);
            }

            return result;
        }


        /// <summary>
        /// Обновление площадки
        /// </summary>
        /// <param name="usersInRoleItem">площадка</param>
        public static void UsersInRolesUpdate(UsersInRoles usersInRoleItem)
        {
            if (usersInRoleItem != null)
            {
                UsersInRoles usersInRoleUpdate = GetUsersInRolebyId(usersInRoleItem.IdUsersInRole);
                if (usersInRoleUpdate != null)
                {
                    usersInRoleUpdate.IdUser = usersInRoleItem.IdUser;
                    usersInRoleUpdate.IdRole = usersInRoleItem.IdRole;

                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление площадки
        /// </summary>
        /// <param name="usersInRoleItem">площадка</param>
        public static void UsersInRolesInsert(UsersInRoles usersInRoleItem)
        {
            Entities.UsersInRoles.AddObject(usersInRoleItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление площадки
        /// </summary>
        /// <param name="usersInRoleItem">площадка</param>
        public static void UsersInRolesDelete(UsersInRoles usersInRoleItem)
        {
            if (usersInRoleItem != null)
            {
                UsersInRoles usersInRoleDel = GetUsersInRolebyId(usersInRoleItem.IdUsersInRole);
                if (usersInRoleDel != null)
                {
                    UsersInRoles.DeleteObject(usersInRoleDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region RolesAccesses

        /// <summary>
        /// Список площадок
        /// </summary>
        public static ObjectSet<RolesAccesses> RolesAccesses
        {
            get { return Entities.RolesAccesses; }
        }

        /// <summary>
        /// Получить площадку по Id
        /// </summary>
        /// <param name="idRolesAccess">Id площадки</param>
        /// <returns>площадка</returns>
        public static RolesAccesses GetRolesAccessbyId(int idRolesAccess)
        {
            RolesAccesses _result = null;
            foreach (RolesAccesses rolesAccess in RolesAccesses)
            {
                if (rolesAccess.IdRolesAccess == idRolesAccess)
                {
                    _result = rolesAccess;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление площадки
        /// </summary>
        /// <param name="rolesAccessItem">площадка</param>
        /// <param name="userLogin"></param>
        public static void RolesAccessesUpdate(RolesAccesses rolesAccessItem, string userLogin)
        {
            if (rolesAccessItem != null)
            {
                RolesAccesses rolesAccessUpdate = GetRolesAccessbyId(rolesAccessItem.IdRolesAccess);
                if (rolesAccessUpdate != null)
                {
                    rolesAccessItem.IdUserLoginModified = userLogin;
                    rolesAccessUpdate.IdRole = rolesAccessItem.IdRole;
                    rolesAccessUpdate.IdControllersAndAction = rolesAccessItem.IdControllersAndAction;
                    rolesAccessUpdate.IdUserLoginModified = rolesAccessItem.IdUserLoginModified;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление площадки
        /// </summary>
        /// <param name="rolesAccessItem">площадка</param>
        /// <param name="userLogin"></param>
        public static void RolesAccessesInsert(RolesAccesses rolesAccessItem, string userLogin)
        {
            rolesAccessItem.IdUserLoginModified = userLogin;
            Entities.RolesAccesses.AddObject(rolesAccessItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление площадки
        /// </summary>
        /// <param name="rolesAccessItem">площадка</param>
        public static void RolesAccessesDelete(RolesAccesses rolesAccessItem)
        {
            if (rolesAccessItem != null)
            {
                RolesAccesses rolesAccessDel = GetRolesAccessbyId(rolesAccessItem.IdRolesAccess);
                if (rolesAccessDel != null)
                {
                    RolesAccesses.DeleteObject(rolesAccessDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region ControllersAndActions

        /// <summary>
        /// Список площадок
        /// </summary>
        public static ObjectSet<ControllersAndActions> ControllersAndActions
        {
            get { return Entities.ControllersAndActions; }
        }

        /// <summary>
        /// Получить площадку по Id
        /// </summary>
        /// <param name="idControllersAndAction">Id площадки</param>
        /// <returns>площадка</returns>
        public static ControllersAndActions GetControllersAndActionbyId(int idControllersAndAction)
        {
            ControllersAndActions _result = null;
            foreach (ControllersAndActions controllersAndAction in ControllersAndActions)
            {
                if (controllersAndAction.IdControllersAndAction == idControllersAndAction)
                {
                    _result = controllersAndAction;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Возвращает Id записи, если найдено совпадение controller и action
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="action"></param>
        /// <returns>ID или 0 если не найдено</returns>
        public static int GetIdControllersAndAction(string controller, string action)
        {
            foreach (var item in ControllersAndActions)
            {
                if (item.Controller == controller && item.Action == action)
                    return item.IdControllersAndAction;
            }
            return 0;
        }

        /// <summary>
        /// Обновление площадки
        /// </summary>
        /// <param name="controllersAndActionItem">площадка</param>
        public static void ControllersAndActionsUpdate(ControllersAndActions controllersAndActionItem)
        {
            if (controllersAndActionItem != null)
            {
                ControllersAndActions controllersAndActionUpdate = GetControllersAndActionbyId(controllersAndActionItem.IdControllersAndAction);
                if (controllersAndActionUpdate != null)
                {
                    controllersAndActionUpdate.Controller = controllersAndActionItem.Controller;
                    controllersAndActionUpdate.Action = controllersAndActionItem.Action;
                    controllersAndActionUpdate.Description = controllersAndActionItem.Description;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление площадки
        /// </summary>
        /// <param name="controllersAndActionItem">площадка</param>
        public static void ControllersAndActionsInsert(ControllersAndActions controllersAndActionItem)
        {

            ControllersAndActions item = new ControllersAndActions();
            //  var item = ControllersAndActions.CreateObject(); 
            //Entities.ControllersAndActions.AddObject(controllersAndActionItem);
            item.Action = controllersAndActionItem.Action;
            item.Controller = controllersAndActionItem.Controller;
            item.Description = "";
            Entities.ControllersAndActions.AddObject(item);
            DB.Save();
        }

        /// <summary>
        /// Удаление площадки
        /// </summary>
        /// <param name="controllersAndActionItem">площадка</param>
        public static void ControllersAndActionsDelete(ControllersAndActions controllersAndActionItem)
        {
            if (controllersAndActionItem != null)
            {
                ControllersAndActions controllersAndActionDel = GetControllersAndActionbyId(controllersAndActionItem.IdControllersAndAction);
                if (controllersAndActionDel != null)
                {
                    ControllersAndActions.DeleteObject(controllersAndActionDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region AddressesTypes

        /// <summary>
        /// Список типов адресов
        /// </summary>
        public static ObjectSet<AddressesTypes> AddressesTypes
        {
            get { return Entities.AddressesTypes; }
        }

        /// <summary>
        /// Активные типы адресов
        /// </summary>
        public static IQueryable<AddressesTypes> AddressesTypesActive
        {
            get
            {
                return
                    AddressesTypes.Where(p => p.IsActive);
            }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedAddressesTypesNames()
        {
            List<LocalizedListItem> result = null;
            foreach (AddressesTypes item in AddressesTypes)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdAddressesType;
                listItem.ParentCollection = AddressesTypes;
                switch (CurrentLanguage)
                {
                    case CurrentLanguage.Russian:
                        listItem.LocaLizedString = item.AddressesTypeRu;
                        break;
                    case CurrentLanguage.English:
                        listItem.LocaLizedString = item.AddressesTypeEn;
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить тип адреса по Id
        /// </summary>
        /// <param name="idAddressesType">Id типа адреса</param>
        /// <returns>тип адреса</returns>
        public static AddressesTypes GetAddressesTypebyId(int idAddressesType)
        {
            AddressesTypes _result = null;
            foreach (AddressesTypes addressesType in AddressesTypes)
            {
                if (addressesType.IdAddressesType == idAddressesType)
                {
                    _result = addressesType;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление типа адреса
        /// </summary>
        /// <param name="addressesTypeItem">тип адреса</param>
        public static void AddressesTypesUpdate(AddressesTypes addressesTypeItem)
        {
            if (addressesTypeItem != null)
            {
                AddressesTypes addressesTypeUpdate = GetAddressesTypebyId(addressesTypeItem.IdAddressesType);
                if (addressesTypeUpdate != null)
                {
                    addressesTypeUpdate.IsActive = addressesTypeItem.IsActive;
                    addressesTypeUpdate.AddressesTypeEn = addressesTypeItem.AddressesTypeEn;
                    addressesTypeUpdate.AddressesTypeRu = addressesTypeItem.AddressesTypeRu;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление типа адреса
        /// </summary>
        /// <param name="addressesTypeItem">тип адреса</param>
        public static void AddressesTypesInsert(AddressesTypes addressesTypeItem)
        {
            Entities.AddressesTypes.AddObject(addressesTypeItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление типа адреса
        /// </summary>
        /// <param name="addressesTypeItem">тип адреса</param>
        public static void AddressesTypesDelete(AddressesTypes addressesTypeItem)
        {
            if (addressesTypeItem != null)
            {
                AddressesTypes addressesTypeDel = GetAddressesTypebyId(addressesTypeItem.IdAddressesType);
                if (addressesTypeDel != null)
                {
                    AddressesTypes.DeleteObject(addressesTypeDel);
                    DB.Save();
                }
            }
        }

        #endregion

        #region RolesTypes

        /// <summary>
        /// Список площадок
        /// </summary>
        public static ObjectSet<RolesTypes> RolesTypes
        {
            get { return Entities.RolesTypes; }
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedRolesTypesNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (RolesTypes item in RolesTypes)
            {
                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdRolesType;
                listItem.ParentCollection = RolesTypes;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.RolesTypeRu;
                }
                else
                {
                    listItem.LocaLizedString = item.RolesTypeEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получить площадку по Id
        /// </summary>
        /// <param name="idRolesType">Id площадки</param>
        /// <returns>площадка</returns>
        public static RolesTypes GetRolesTypebyId(int idRolesType)
        {
            RolesTypes _result = null;
            foreach (RolesTypes rolesType in RolesTypes)
            {
                if (rolesType.IdRolesType == idRolesType)
                {
                    _result = rolesType;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление площадки
        /// </summary>
        /// <param name="rolesTypeItem">площадка</param>
        public static void RolesTypesUpdate(RolesTypes rolesTypeItem)
        {
            if (rolesTypeItem != null)
            {
                RolesTypes rolesTypeUpdate = GetRolesTypebyId(rolesTypeItem.IdRolesType);
                if (rolesTypeUpdate != null)
                {
                    rolesTypeUpdate.RolesTypeEn = rolesTypeItem.RolesTypeEn;
                    rolesTypeUpdate.RolesTypeRu = rolesTypeItem.RolesTypeRu;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление площадки
        /// </summary>
        /// <param name="rolesTypeItem">площадка</param>
        public static void RolesTypesInsert(RolesTypes rolesTypeItem)
        {
            Entities.RolesTypes.AddObject(rolesTypeItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление площадки
        /// </summary>
        /// <param name="rolesTypeItem">площадка</param>
        public static void RolesTypesDelete(RolesTypes rolesTypeItem)
        {
            if (rolesTypeItem != null)
            {
                RolesTypes rolesTypeDel = GetRolesTypebyId(rolesTypeItem.IdRolesType);
                if (rolesTypeDel != null)
                {
                    RolesTypes.DeleteObject(rolesTypeDel);
                    DB.Save();
                }
            }
        }





        #endregion

        #region UserInRoles

        /// <summary>
        /// Проверяет принадлежность логина пользователя типу группы
        /// </summary>
        /// <param name="idRoleType"></param>
        /// <param name="userLoginName"></param>
        /// <returns></returns>
        public static bool IsUserInRoleType(int idRoleType, string userLoginName)
        {
            List<Roles> rolesList = GetRolesByUserLoginname(userLoginName);
            if (rolesList != null)
            {
                return rolesList.Any(role => role.IdRolesType == idRoleType);
            }
            return false;
        }

        /// <summary>
        /// Пользователь имеет тип роли?
        /// </summary>
        /// <param name="idRoleType">Идентификатор типа роли</param>
        /// <param name="user">Пользователь</param>
        /// <returns>Да/нет</returns>
        public static bool IsUserInRoleType(int idRoleType, Users user)
        {
            List<Roles> rolesList = GetRolesByUser(user);
            if (rolesList != null)
            {
                return rolesList.Any(role => role.IdRolesType == idRoleType);
            }
            return false;
        }

        /// <summary>
        /// Возвращает список имен пользователей по типу роли
        /// </summary>
        /// <param name="idRoleType"></param>
        /// <returns></returns>
        public static List<Users> GetUsersByRoleType(int idRoleType)
        {
            List<Users> result = new List<Users>();
            foreach (var role in Roles)
            {
                if (role.IdRolesType == idRoleType)
                {
                    UsersInRoles user = GetUsersInRolebyId(role.IdRole);
                    if (user != null)
                    {
                        if (result.Contains(user.Users))
                        {
                            result.Add(user.Users);
                        }
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// Возвращает список имен пользователей по типу роли и региону профайн
        /// </summary>
        /// <param name="idRoleType"></param>
        /// <param name="idProfineRegion"></param>
        /// <returns></returns>
        public static List<Users> GetUsersByRoleTypeAndIdProfineRegion(int idRoleType, int idProfineRegion)
        {
            List<Users> result = new List<Users>();
            foreach (var role in Roles)
            {
                if (role.IdRolesType == idRoleType && role.IdProfineRegion == idProfineRegion)
                {
                    UsersInRoles user = GetUsersInRolebyId(role.IdRole);
                    if (user != null)
                    {
                        if (result.Contains(user.Users))
                        {
                            result.Add(user.Users);
                        }
                    }
                }
            }
            return result;
        }



        #endregion

        #region Users


        /// <summary>
        /// Возвращает список пользователей, отсортированнй по полному русскому имени
        /// </summary>
        public static IEnumerable<Users> Users
        {
            get
            {
                return Entities.Users.OrderBy(user => user.UserFullNameRu);
            }
        }


        ///// <summary>
        ///// Получение пользователя из AD
        ///// </summary>
        ///// <param name="login">Логин</param>
        ///// <returns>Пользователь</returns>
        //public static Users GetUserNameFromADByLogin(string login)
        //{
        //    Users result = new Users();
        //    login = login.ToUpper().Replace(@"RU\", "");
        //    DirectorySearcher ds = new DirectorySearcher();
        //    ds.Filter = "(objectCategory=user)";
        //    SearchResultCollection sr = ds.FindAll();
        //    foreach (SearchResult s in sr)
        //    {
        //        foreach (object o in s.Properties["samaccountname"])
        //        {
        //            if (o.ToString().ToUpper() == login)
        //            {
        //                try
        //                {
        //                    result.UserFullNameEn = s.Properties["displayname"][0] as string;//descriptio
        //                    result.UserFullNameRu = s.Properties["description"][0] as string;
        //                    result.UserLogin = login;

        //                    return result;
        //                }
        //                catch
        //                {
        //                }
        //            }

        //        }
        //    }


        //    return null;
        //}


        /// <summary>
        /// Проверка пользователя
        /// </summary>
        /// <param name="user">Пользователь</param>
        /// <returns>Результат проверки</returns>
        public static bool ValidateUser(Users user)
        {
            if (!string.IsNullOrEmpty(user.UserFullNameEn) && !string.IsNullOrEmpty(user.UserFullNameRu) && !string.IsNullOrEmpty(user.UserLogin))
                return true;
            return false;
        }

        /// <summary>
        /// Получение имени пользователя по логину
        /// </summary>
        /// <param name="login">Логин</param>
        /// <returns>Имя пользователя</returns>
        public static Users GetUserByLogin(string login)
        {
            if (string.IsNullOrEmpty(login))
                return null;
            if (login.Length < 6)
                return null;

            Users user = null;

            foreach (var item in Users)
            {
                if (item.UserLogin.ToUpper().Replace(@"RU\", "") == login.ToUpper().Replace(@"RU\", ""))
                {
                    return item;
                }
            }


            //= Users.FirstOrDefault(p => login != null && (p.UserLogin != null && p.UserLogin.ToUpper() == login.ToUpper()));
            //if (user==null)
            //{
            //    user = Users.FirstOrDefault(p => login != null && (p.UserLogin != null && p.UserLogin.ToUpper().Replace(@"RU/", "") == login.ToUpper().Replace(@"RU/", "")));    
            //}

            //if (user == null)
            //{

            //    user = GetUserNameFromADByLogin(login);
            //    UsersInsert(user);
            //    //    return null;
            //}

            //if (!ValidateUser(user))
            //{
            //    UpdateUserInfo(user);
            //}

            return user;
        }

        //public static void UpdateUserInfo(Users user)
        //{
        //    var usernew = GetUserNameFromADByLogin(user.UserLogin);
        //    user.UserFullNameRu = usernew != null ? usernew.UserFullNameRu : user.UserFullNameEn;
        //    UsersUpdate(user);
        //}

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedUsersNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (Users item in Users)
            {
                if (!ValidateUser(item))
                {
                //    UpdateUserInfo(item);
                }

                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdUser;
                listItem.ParentCollection = Users;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.UserFullNameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.UserFullNameEn;
                }
                result.Add(listItem);
            }
            return result;
        }

        /// <summary>
        /// Получение локализованного списка значений
        /// </summary>
        /// <param name="culture"></param>
        /// <returns></returns>
        public static List<LocalizedListItem> GetLocalizedManagersNames(string culture)
        {
            List<LocalizedListItem> result = null;
            foreach (Users item in Managers)
            {
                if (!ValidateUser(item))
                {
                  //  UpdateUserInfo(item);
                }

                if (result == null) result = new List<LocalizedListItem>();
                var listItem = new LocalizedListItem();
                listItem.Id = item.IdUser;
                listItem.ParentCollection = Users;
                if (culture.Contains("ru"))
                {
                    listItem.LocaLizedString = item.UserFullNameRu;
                }
                else
                {
                    listItem.LocaLizedString = item.UserFullNameEn;
                }
                result.Add(listItem);
            }
            return result;
        }


        /// <summary>
        /// Менеджеры
        /// </summary>
        public static IEnumerable<Users> Managers
        {
            get
            {
                return Users.Where(user => DB.IsUserInRoleType(2, user)).ToList();
            }
        }


        /// <summary>
        /// Получить пользователя по Id
        /// </summary>
        /// <param name="idUser">Id пользователя</param>
        /// <returns>пользователь</returns>
        public static Users GetUserbyId(int idUser)
        {
            Users _result = null;
            foreach (Users user in Users)
            {
                if (user.IdUser == idUser)
                {
                    _result = user;
                    break;
                }
            }
            return _result;
        }

        /// <summary>
        /// Обновление пользователя
        /// </summary>
        /// <param name="userItem">пользователь</param>
        public static void UsersUpdate(Users userItem)
        {
            if (userItem != null)
            {
                Users userUpdate = GetUserbyId(userItem.IdUser);
                if (userUpdate != null)
                {
                    userUpdate.UserFullNameEn = userItem.UserFullNameEn;
                    userUpdate.UserFullNameRu = userItem.UserFullNameRu;
                    userUpdate.UserLogin = userItem.UserLogin;
                    DB.Save();
                }
            }
        }

        /// <summary>
        /// Добавление пользователя
        /// </summary>
        /// <param name="userItem">пользователь</param>
        public static void UsersInsert(Users userItem)
        {
            Entities.Users.AddObject(userItem);
            DB.Save();
        }

        /// <summary>
        /// Удаление пользователя
        /// </summary>
        /// <param name="userItem">пользователь</param>
        public static void UsersDelete(Users userItem)
        {
            if (userItem != null)
            {
                Users userDel = GetUserbyId(userItem.IdUser);
                if (userDel != null)
                {
                    Entities.Users.DeleteObject(userDel);
                    DB.Save();
                }
            }
        }

        #endregion

    }

    /// <summary>
    /// Локализованный список
    /// </summary>
    public class LocalizedListItem
    {
        /// <summary>
        /// Идентификатор в родительской коллекции
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// Локализованная строка
        /// </summary>
        public string LocaLizedString { get; set; }

        /// <summary>
        /// Родительская коллекция
        /// </summary>
        public object ParentCollection { get; set; }
    }



    /// <summary>
    /// Класс для представления параметров фильтра
    /// </summary>
    public class FilterItem
    {
        /// <summary>
        /// Начало периода
        /// </summary>
        private DateTime _periodStart;


        /// <summary>
        /// Окончание периода
        /// </summary>
        private DateTime _periodEnd;

        /// <summary>
        /// Идентификатор региона профайн
        /// </summary>
        private int _idProfineRegion;

        /// <summary>
        /// Идентификатор менеджера
        /// </summary>
        private string _idManager;

        /// <summary>
        /// Начало периода
        /// </summary>
        public DateTime PeriodStart
        {
            get { return _periodStart; }
            set { _periodStart = value; }
        }

        /// <summary>
        /// Окончание периода
        /// </summary>
        public DateTime PeriodEnd
        {
            get { return _periodEnd; }
            set { _periodEnd = value; }
        }

        /// <summary>
        /// Идентификатор региона профайн
        /// </summary>
        public int IdProfineRegion
        {
            get { return _idProfineRegion; }
            set { _idProfineRegion = value; }
        }

        /// <summary>
        /// Идентификатор менеджера
        /// </summary>
        public string IdManager
        {
            get { return _idManager; }
            set { _idManager = value; }
        }
    }

    public enum CurrentLanguage
    {
        Russian = 0,
        English = 1
    }




}
